Esempio n. 1
0
        public IActionResult Post([FromBody] Admin value)
        {
            AdminRepo admin = new AdminRepo();
            var       temp  = admin.insert(value);

            return(Ok(temp));
        }
Esempio n. 2
0
        public IActionResult Token()
        {
            var header = Request.Headers["Authorization"];

            if (header.ToString().StartsWith("Basic"))
            {
                var credvalue          = header.ToString().Substring("Basic ".Length).Trim();
                var usernameAndPassenc = Encoding.UTF8.GetString(Convert.FromBase64String(credvalue));
                var usernameAndPass    = usernameAndPassenc.Split(":");

                AdminRepo login     = new AdminRepo();
                var       listLogin = login.getAll();

                foreach (var temp in listLogin)
                {
                    if (usernameAndPass[0] == temp.Username && usernameAndPass[1] == temp.Password)
                    {
                        var claimsdata = new[] { new Claim(ClaimTypes.Name, temp.Username) };
                        var key        = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("aowue92187183123nb1273131g9182"));
                        var signInCred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
                        var token      = new JwtSecurityToken(
                            issuer: "mysite.com",
                            audience: "mysite.com",
                            expires: DateTime.Now.AddMinutes(1),
                            claims: claimsdata,
                            signingCredentials: signInCred
                            );
                        var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
                        return(Ok(tokenString));
                    }
                }
            }

            return(BadRequest("Wrong Request"));
        }
Esempio n. 3
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");



                    var guid = AdminRepo.GetId(model.Email);
                    AdminRepo.InsertNewUserToDb(model, guid);

                    return(RedirectToAction("RegisterSuccess", "Account"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 4
0
        static async Task <int> Main(string[] args)
        {
            MxReturnCode <int> rc = new MxReturnCode <int>($"{Program.WebAppName} v{Program.WebAppVersion}", 1);

            rc.Init(Assembly.GetExecutingAssembly(), "*****@*****.**", null, null, null, MxMsgs.SupportedCultures);

            Console.WriteLine(rc.GetInvokeDetails());

            var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("local.settings.json")
                         .Build();
            var conn = config?["ConnectionStrings:DefaultConnection"];  //03-12-18

            if (conn == null)
            {
                rc.SetError(2010101, MxError.Source.AppSetting, "config not built or ConnectionStrings:DefaultConnection not found");
            }
            else
            {
                using (IAdminRepo repo = new AdminRepo(conn))
                {
                    rc += await repo.GetUrdCountAsync();
                }
                if (rc.IsSuccess(true))
                {
                    Console.WriteLine($"Roles found = {rc.GetResult()}");
                    rc.SetResult(0);
                }
            }
            Console.WriteLine(rc.IsError(true) ? rc.GetErrorUserMsg() : $"Hello World!");
            Console.WriteLine(rc.IsError(true) ? rc.GetErrorTechMsg(): "no error");

            return(rc.GetResult());
        }
Esempio n. 5
0
        private ActionResult RedirectToLocal(string returnUrl, int id)
        {
            var userRole = AdminRepo.GetUserRoles(id).FirstOrDefault();

            if (Url.IsLocalUrl(returnUrl))
            {
                return(Redirect(returnUrl));
            }
            if (userRole == "Admin")
            {
                return(RedirectToAction("AdminDashboard", "Admin", new { id }));
            }
            if (userRole == "Teacher")
            {
                return(RedirectToAction("TeacherDashboard", "Teacher", new { id }));
            }
            if (userRole == "Student")
            {
                return(RedirectToAction("StudentDashboard", "Student", new { id }));
            }
            if (userRole == "Parent")
            {
                return(RedirectToAction("ParentDashboard", "Student", new { id }));
            }
            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 6
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result =
                await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                int id = AdminRepo.GetUserIdByEmail(model.Email);
                return(RedirectToLocal(returnUrl, id));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
Esempio n. 7
0
        public void GetAdminListAsyncShouldReturnResult()
        {
            // arrange
            var options = new DbContextOptionsBuilder <PH_DbContext>()
                          .UseInMemoryDatabase("GetAdminListAsyncShouldReturnResult")
                          .Options;

            using var arrangeContext = new PH_DbContext(options);

            var id      = 5;
            var UserId  = 10;
            var newUser = new Users {
                Email = "dude"
            };

            arrangeContext.Admin.Add(new Admins {
                Id = id, UsersID = UserId, User = newUser
            });
            arrangeContext.SaveChanges();

            using var actContext = new PH_DbContext(options);
            var repo = new AdminRepo(actContext);

            // act
            var result = repo.GetAdminListAsync();

            // assert
            Assert.NotNull(result);
        }
Esempio n. 8
0
 public Admin GetByUserName(string userName)
 {
     using (var ctx = DbContext(DbOperation.Read))
     {
         var repo = new AdminRepo(ctx);
         return(repo.GetByUserName(userName));
     }
 }
        public AdminPanel()
        {
            InitializeComponent();

            this.ad = new AdminRepo();
            List <Admin> listofAdmin = ad.GetAllAdmin();

            adminDGV.DataSource = listofAdmin;
        }
Esempio n. 10
0
        private async Task <List <Account> > GetUsers()
        {
            var userList = new List <Account>();

            userList.AddRange(await AdminRepo.GetAllItemsAsync());
            userList.AddRange(await DeveloperRepo.GetAllItemsAsync());
            userList.AddRange(await RecruiterRepo.GetAllItemsAsync());
            return(userList);
        }
Esempio n. 11
0
        public ActionResult Profile(int id)
        {
            var result = AdminRepo.GetByID(id);

            return(View(result.Data ?? new Admins()
            {
                Users = new Users(), JoinDate = DateTime.Now
            }));
        }
Esempio n. 12
0
        public ActionResult List(string key = "")
        {
            var result = AdminRepo.GetAll(key);

            if (TempData["Error"] != null)
            {
                ViewBag.Error = TempData["Error"];
            }
            return(View(result));
        }
Esempio n. 13
0
        public ActionResult Delete(int id)
        {
            var result = AdminRepo.Delete(id);

            if (result.HasError)
            {
                TempData["Error"] = result.Message;
            }
            return(RedirectToAction("List"));
        }
Esempio n. 14
0
 public EditRecordViewModel(string tableName, object id)
 {
     Title             = "Edit Column";
     this.tableName    = tableName;
     this.id           = id;
     Columns           = new ObservableCollection <Column>();
     userRepo          = new UserRepo(App.Database);
     adminRepo         = new AdminRepo(App.Database);
     roomRepo          = new RoomRepo(App.Database);
     EditRecordCommand = new Command(() => ExecuteEditRecordCommand());
 }
Esempio n. 15
0
 public AddRecordViewModel(string tableName)
 {
     Title              = "Add Column";
     this.tableName     = tableName;
     Columns            = new ObservableCollection <Column>();
     LoadColumnsCommand = new Command(() => ExecuteLoadColumnsCommand());
     AddRecordCommand   = new Command(() => ExecuteAddRecordCommand());
     userRepo           = new UserRepo(App.Database);
     adminRepo          = new AdminRepo(App.Database);
     roomRepo           = new RoomRepo(App.Database);
 }
Esempio n. 16
0
        public ActionResult Login(Admin model)
        {
            var result = AdminRepo.AdminValid(model);

            if (result != null)
            {
                Session["Id"]       = result.Id;
                Session["NickName"] = result.NickName;
            }

            return(RedirectToAction("Index"));
        }
Esempio n. 17
0
 public ActionResult Login(Admin model)
 {
     using (YemekDBContext db = new YemekDBContext())
     {
         var result = AdminRepo.AdminLogin(model);
         if (result != null)
         {
             FormsAuthentication.SetAuthCookie(model.Email, true);
             return(RedirectToAction("Add", "Admin"));
         }
         return(View());
     }
 }
Esempio n. 18
0
        public async Task <IActionResult> OnGetAsync()
        {
            MxReturnCode <IActionResult> rc = new MxReturnCode <IActionResult>("Index.OnGetAsync()", Page());

            var userID = "[nobody logged-in]";
            var msg    = "unknown error";

            try
            {
                var loggedInUser = await _userManager.GetUserAsync(User);

                userID = loggedInUser?.Id ?? "[nobody logged-in]";
                msg    = $"{loggedInUser?.UserName ?? "nobody"} is logged-in. ";
                if (loggedInUser?.EmailConfirmed == false)
                {
                    msg += "Check your emails to complete your registration";
                }

                using (IAdminRepo repo = new AdminRepo(_config?.GetConnectionString("DefaultConnection")))
                {
                    var resCnt = await repo.GetUrdCountAsync();

                    rc += resCnt;
                    if (rc.IsError())
                    {
                        DatabaseStatus = "Database access failed";
                    }
                    else
                    {
                        DatabaseStatus = $"Database access ok, Role Count = {resCnt.GetResult()}";
                        rc.SetResult(Page());
                    }
                }
            }
            catch (Exception e)
            {
                rc.SetError(3040101, MxError.Source.Exception, e.Message, MxMsgs.MxErrUnknownException, true);
            }
            if (rc.IsError(true))
            {
                SetPageStatusMsg(rc.GetErrorUserMsgHtml(userID), ExistingMsg.Overwrite);
            }
            else
            {
                SetPageStatusMsg(msg, ExistingMsg.Overwrite);
            }

            return(rc.GetResult());
        }
        public ViewResult LoginAdmin(Admin adm)
        {
            bool isLogin = false;

            AdminRepo.Login(adm.Code, ref isLogin);
            if (isLogin)
            {
                List <PublicUser> users = PublicUserRepo.GetAllUsers();
                return(View("AdminDash", users));
            }
            else
            {
                ModelState.AddModelError(String.Empty, "Please enter correct data");
                return(View());
            }
        }
Esempio n. 20
0
        public IActionResult Put([FromBody] Admin value)
        {
            AdminRepo admin = new AdminRepo();

            if (admin.update(value) == true)
            {
                return(Ok(value));
            }
            else
            {
                var response = new ContentResult()
                {
                    StatusCode = StatusCodes.Status404NotFound,
                };
                return(response);
            }
        }
        public ActionResult GET(Admin model)
        {
            var admin = AdminRepo.Get(model);

            if (admin != null)
            {
                Session["ID"]       = admin.AdminID;
                Session["UserName"] = admin.UserName;
                Session["Password"] = admin.Password;
                return(RedirectToAction("Index", "Dashboard"));
            }
            else
            {
                Response.Write("Kullanıcı Bulunamadı!");
                return(View());
            }
        }
Esempio n. 22
0
        public ActionResult Profile(Admins admins)
        {
            if (!ModelState.IsValid)
            {
                return(View(admins));
            }

            var result = AdminRepo.Save(admins);

            if (result.HasError)
            {
                ViewBag.Error = result.Message;
                return(View(admins));
            }

            return(RedirectToAction("Index"));
        }
        private static void CreateAdminUsersIfNotExist(IHost host)
        {
            using var scope = host.Services.CreateScope();
            var services = scope.ServiceProvider;

            var context = services.GetRequiredService <TestSwitchDbContext>();

            context.Database.EnsureCreated();
            IAdminRepo adminRepo = new AdminRepo(context);

            if (!context.AdminUsers.Any())
            {
                string newAdminEmail    = Environment.GetEnvironmentVariable("DEFAULT_ADMIN_EMAIL");
                string newAdminPassword = Environment.GetEnvironmentVariable("DEFAULT_ADMIN_PASSWORD");
                adminRepo.CreateNewAdminUser(newAdminEmail, newAdminPassword);
            }
        }
Esempio n. 24
0
        public IActionResult Get()
        {
            AdminRepo admin     = new AdminRepo();
            var       listAdmin = admin.getAll();

            if (listAdmin == null)
            {
                var response = new ContentResult()
                {
                    StatusCode = StatusCodes.Status204NoContent,
                };
                return(response);
            }
            else
            {
                return(Ok(listAdmin));
            }
        }
Esempio n. 25
0
        public IActionResult Get(int id)
        {
            AdminRepo admin = new AdminRepo();
            var       hasil = admin.getById(id);

            if (hasil == null)
            {
                var response = new ContentResult()
                {
                    StatusCode = StatusCodes.Status204NoContent,
                };
                return(response);
            }
            else
            {
                return(Ok(hasil));
            }
        }
Esempio n. 26
0
        public void GetReportedUsers_WithLimitAndOffset_RetrievesExpectedUsersInAllCases(int limit, int offset, List <UserShortVersion> expected)
        {
            //arrange
            using (DummyDbContext ctx = new DummyDbContext())
            {
                IAdminRepoTest adminRepo = new AdminRepo();

                //act
                List <UserShortVersion> actual = adminRepo.GetAdminUsersWithDbContextAsync(ctx, limit, offset);

                //assert
                Assert.Equal(expected.Count, actual.Count);
                for (int i = 0; i < actual.Count; i++)
                {
                    Assert.Equal(expected[i].UserId, actual[i].UserId);
                    Assert.Equal(expected[i].UserFullName, actual[i].UserFullName);
                }
            }
        }
Esempio n. 27
0
        public IActionResult Delete(int id)
        {
            AdminRepo admin = new AdminRepo();
            Admin     ad    = new Admin();

            ad.Id = id;
            if (admin.delete(ad) == true)
            {
                return(Ok(ad));
            }
            else
            {
                var response = new ContentResult()
                {
                    StatusCode = StatusCodes.Status404NotFound,
                };
                return(response);
            }
        }
        private void Register_Click(object sender, EventArgs e)
        {
            Admin a = new Admin();

            a.Id       = idTB.Text;
            a.Name     = nameTB.Text;
            a.Contact  = contactTB1.Text + contactTB2.Text;
            a.Password = passwordTB.Text;

            AdminRepo aRepo = new AdminRepo();



            MessageBox.Show("" + a.Id + a.Name + a.Contact + a.Password);
            if (aRepo.InsertAdmin(a) && aRepo.InsertLogin(a))
            {
                MessageBox.Show("admin inserted");
            }
            else
            {
                MessageBox.Show("admin not inserted");
            }
        }
        public int CountAdministrators()
        {
            var count = AdminRepo.Count();

            return(count);
        }
 public bool IsAdmin(string userIdentityName)
 {
     return(AdminRepo.Read(m => m.UserIdentityName == userIdentityName).Any());
 }