Ejemplo n.º 1
0
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new SchoolUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

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

                        _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
Ejemplo n.º 2
0
        private bool Validate(SchoolYearViewModel data, SchoolUser user)
        {
            var IsValid = true;

            //check for overlapping dates from existing school years
            var sys = _sy.GetSchoolYears(user.School.Id);

            foreach (var sy in sys.Where(o => o.Id != data.Id))
            {
                if (sy.Start.Value <= data.Start.Value && data.Start.Value <= sy.End.Value)
                {
                    AddPageAlerts(PageAlertType.Warning, "Your date range is overlapping to " + sy.Name + "!");
                    IsValid = false;
                    break;
                }
                else if (sy.Start.Value <= data.End.Value && data.End.Value <= sy.End.Value)
                {
                    AddPageAlerts(PageAlertType.Warning, "Your date range is overlapping to " + sy.Name + "!");
                    IsValid = false;
                    break;
                }
                if (sy.Name.ToLower().Trim() == data.Name.ToLower().Trim())
                {
                    AddPageAlerts(PageAlertType.Warning, "The name you use has already exist!");
                    IsValid = false;
                    break;
                }
            }
            return(IsValid);
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Register(RegisterViewModel registerViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(registerViewModel));
            }

            var user = new SchoolUser
            {
                UserName = registerViewModel.UserName,
                Email    = registerViewModel.Email
            };

            var result = await _userManager.CreateAsync(user, registerViewModel.Password);

            if (result.Succeeded)
            {
                var confirmationCode = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                var callBackUrl = Url.Action("ConfirmEmail", "Security", new
                {
                    userId = HttpUtility.UrlEncode(user.Id),
                    code   = HttpUtility.UrlEncode(confirmationCode)
                });

                await _emailSender.SendEmailAsync(user.Email, "Lütfen Mailinizi Onaylayınız.",
                                                  $"Hesabınızı onaylamak için <a href='https://localhost:5001{callBackUrl}'>buraya</a> tıklayınız!");

                return(RedirectToAction("Login"));
            }

            return(View(registerViewModel));
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> Create(CreateVm createVm)
        {
            if (ModelState.IsValid)
            {
                SchoolUser user = new SchoolUser
                {
                    UserName = createVm.Email,
                    Email    = createVm.Email,
                    //extended properties
                    FirstName = createVm.FirstName,
                    LastName  = createVm.LastName,
                };

                IdentityResult result = await userManager.CreateAsync(user, createVm.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    foreach (IdentityError error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }
            return(View(createVm));
        }
        public async Task <ResponseResult <StudentViewModel> > AddStudent(StudentViewModel data, SchoolProfile school)
        {
            using (var trans = _context.Database.BeginTransaction())
            {
                var r         = Shared.String.GenerateRandom(_settings.StudentIdLength, false, true, false, false);
                var studentId = $"{school.Code}{r}";
                //check if studentID already exist
                while (_manager.GetList(o => o.StudentId == studentId).Count() > 0)
                {
                    r         = Shared.String.GenerateRandom(_settings.StudentIdLength, false, true, false, false);
                    studentId = $"{school.Code}{r}";
                }
                var username = $"{studentId}@{school.Name.Replace(" ", "_")}.com";
                var user     = new SchoolUser
                {
                    UserName       = username,
                    Email          = username,
                    EmailConfirmed = true,
                    //extended properties
                    FirstName        = data.FirstName,
                    LastName         = data.LastName,
                    School           = school,
                    Type             = UserType.Student,
                    InsertedDateTime = DateTime.Now,
                    UpdatedDateTime  = DateTime.Now
                };

                var password = $"{data.LastName.ToProperCase()}{r}!";
                var result   = await _userManager.CreateAsync(user, password);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, "Student");

                    var student = await _manager.AddAsync(new Model.StudentProfile()
                    {
                        FirstName  = data.FirstName,
                        LastName   = data.LastName,
                        MiddleName = data.MiddleName,
                        Gender     = data.Gender,
                        DOB        = data.DOB,
                        Email      = data.Email,
                        Phone      = data.Phone,
                        Mobile     = data.Mobile,
                        StudentId  = studentId,

                        School = school,
                        User   = user
                    });

                    data.Id = student.Id;
                    await trans.CommitAsync();
                }
            }

            return(ResponseResult <StudentViewModel> .SetSuccess(data));
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                using (var trans = _context.Database.BeginTransaction())
                {
                    var schoolCode = Shared.String.GenerateRandom(_settings.SchoolCodeLength, true, false, false, true);
                    while (_schoolManager.GetAll().Where(o => o.Code == schoolCode).Count() > 0)
                    {
                        schoolCode = Shared.String.GenerateRandom(_settings.SchoolCodeLength, true, false, false, true);
                    }
                    var school = await _schoolManager.AddAsync(new SchoolProfile
                    {
                        Id            = Guid.NewGuid(),
                        ContactNumber = model.ContactNumber,
                        FirstName     = model.FirstName,
                        LastName      = model.LastName,
                        Name          = model.SchoolName,
                        Code          = schoolCode
                    });;
                    var user = new SchoolUser
                    {
                        UserName = model.Email,
                        Email    = model.Email,
                        //extended properties
                        FirstName        = model.FirstName,
                        LastName         = model.LastName,
                        School           = school,
                        Type             = UserType.Admin,
                        InsertedDateTime = DateTime.Now,
                        UpdatedDateTime  = DateTime.Now
                    };
                    var result = await _userManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        await _userManager.AddToRoleAsync(user, "Admin");

                        // Send an email with this link
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                        await _emailSender.SendEmailAsync(model.Email, "Confirm your account", $"Please confirm your account by clicking this: <a href='{callbackUrl}'>link</a>");

                        _logger.LogInformation(3, "User created a new account with password.");
                        await trans.CommitAsync();

                        return(RedirectToAction(nameof(SuccessRegister)));
                    }
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> ChangePassword(string id, string password)
        {
            SchoolUser user = await userManager.FindByIdAsync(id);

            if (user != null)
            {
                // Validate password
                // Step 1: using built in validations
                IdentityResult passwordResult = await userManager.CreateAsync(testUser, password);

                if (passwordResult.Succeeded)
                {
                    await userManager.DeleteAsync(testUser);
                }
                else
                {
                    AddErrors(passwordResult);
                }

                /* Step 2: Because of DI, IPasswordValidator<User> is injected into the custom password validator.
                 * So the built in password validation stop working here */
                IdentityResult validPasswordResult = await passwordValidator.ValidateAsync(userManager, user, password);

                if (validPasswordResult.Succeeded)
                {
                    user.PasswordHash = passwordHasher.HashPassword(user, password);
                }
                else
                {
                    AddErrors(validPasswordResult);
                }

                // Update user info
                if (passwordResult.Succeeded && validPasswordResult.Succeeded)
                {
                    // UpdateAsync validates user info such as UserName and Email except password since it's been hashed
                    IdentityResult result = await userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Index", "SuperAdmin"));
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "User Not Found");
            }

            return(View(user));
        }
        public async Task <IActionResult> Edit(ModifyRoleVm modifyRole)
        {
            IdentityResult result;

            if (ModelState.IsValid)
            {
                IdentityRole role = await roleManager.FindByIdAsync(modifyRole.RoleId);

                role.Name = modifyRole.RoleName;
                result    = await roleManager.UpdateAsync(role);

                if (!result.Succeeded)
                {
                    AddErrors(result);
                }

                foreach (string userId in modifyRole.IdsToAdd ?? new string[] { })
                {
                    SchoolUser user = await userManager.FindByIdAsync(userId);

                    if (user != null)
                    {
                        result = await userManager.AddToRoleAsync(user, modifyRole.RoleName);

                        if (!result.Succeeded)
                        {
                            AddErrors(result);
                        }
                    }
                }

                foreach (string userId in modifyRole.IdsToRemove ?? new string[] { })
                {
                    SchoolUser user = await userManager.FindByIdAsync(userId);

                    if (user != null)
                    {
                        result = await userManager.RemoveFromRoleAsync(user, modifyRole.RoleName);

                        if (!result.Succeeded)
                        {
                            AddErrors(result);
                        }
                    }
                }
            }

            if (ModelState.IsValid)
            {
                return(RedirectToAction("Index"));
            }

            return(View(modifyRole.RoleId));
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            Input.ClassGroupName = await _classGroupRepository.GetById(SelectedClassGroupId);

            Input.SchoolUserCategory = await _schoolUserCategoryRepository.GetById(SelectedSchoolUserCategoryId);

            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    UserName = Input.LastName + "." + Input.FirstName                          /*, Email = Input.Email */
                };

                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    //await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                    //    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    //await _signInManager.SignInAsync(user, isPersistent: false);
                    string[] fullname   = user.UserName.Split(".");
                    var      schoolUser = new SchoolUser
                    {
                        IdentityReference = user.Id,
                        FirstName         = fullname[1],
                        Id                 = Guid.NewGuid(),
                        LastName           = fullname[0],
                        ClassGroup         = Input.ClassGroupName,
                        SchoolUserCategory = Input.SchoolUserCategory
                    };
                    await _schoolUserController.Create(schoolUser);

                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Ejemplo n.º 10
0
        public async Task <User> RegisterSchoolUser(SchoolUser schoolUser)
        {
            var accountRegister = new FullRegisterInputModel
            {
                Pin       = schoolUser.Pin,
                FirstName = schoolUser.FirstName,
                LastName  = schoolUser.LastName,
                RoleName  = schoolUser.Role.ToString()
            };

            return(await Register(accountRegister));
        }
Ejemplo n.º 11
0
        private static string GetFullName(SchoolUser user)
        {
            var fullName = user.FirstName;

            if (user.SecondName != null)
            {
                fullName += ' ' + user.SecondName;
            }

            fullName += ' ' + user.LastName;
            return(fullName);
        }
        public LoginResult GetLoginResult(SchoolUser user)
        {
            DateTime willExpireOn = DateTime.UtcNow.AddMinutes(5);
            var      result       = new LoginResult()
            {
                UserId         = user.Id,
                ExpirationDate = willExpireOn,
                Token          = GenerateJwtToken(user.Id, willExpireOn)
            };

            return(result);
        }
Ejemplo n.º 13
0
        private async Task <User> CreateAspUser(SchoolUser schoolUser, RoleTypes role)
        {
            var accountRegister = new FullRegisterInputModel
            {
                Pin       = schoolUser.Pin,
                FirstName = schoolUser.FirstName,
                LastName  = schoolUser.LastName,
                RoleName  = role.ToString()
            };

            return(await _accountService.Register(accountRegister));
        }
Ejemplo n.º 14
0
 public async Task <SchoolUser> Update(SchoolUser entity)
 {
     _oefenplatformContext.Entry(entity).State = EntityState.Modified;
     try
     {
         await _oefenplatformContext.SaveChangesAsync();
     }
     catch
     {
         return(null);
     }
     return(entity);
 }
Ejemplo n.º 15
0
        public async Task <IActionResult> ChangePassword(string id)
        {
            SchoolUser user = await userManager.FindByIdAsync(id);

            if (user != null)
            {
                return(View(user));
            }
            else
            {
                return(RedirectToAction("Index"));
            }
        }
Ejemplo n.º 16
0
 public async Task <SchoolUser> Delete(SchoolUser entity)
 {
     _oefenplatformContext.Set <SchoolUser>().Remove(entity);
     try
     {
         await _oefenplatformContext.SaveChangesAsync();
     }
     catch
     {
         return(null);
     }
     return(entity);
 }
Ejemplo n.º 17
0
        public async Task <ResponseResult <SchoolTeacherViewModel> > AddTeacher(SchoolTeacherViewModel data, SchoolProfile school)
        {
            using (var trans = _context.Database.BeginTransaction())
            {
                var r        = Shared.String.GenerateRandom(4, false, true, false, false);
                var username = $"{data.FirstName[0]}{data.LastName.ToLower()}_{r}@{school.Name.Replace(" ", "_")}.com";

                //check if studentID already exist
                while (_manager.GetList(o => o.User.UserName == username, o => o.User).Count() > 0)
                {
                    r        = Shared.String.GenerateRandom(4, false, true, false, false);
                    username = $"{data.FirstName[0]}{data.LastName.ToLower()}_{r}@{school.Name.Replace(" ", "_")}.com";
                }

                var user = new SchoolUser
                {
                    UserName       = username,
                    Email          = username,
                    EmailConfirmed = true,
                    //extended properties
                    FirstName        = data.FirstName,
                    LastName         = data.LastName,
                    School           = school,
                    Type             = UserType.Teacher,
                    InsertedDateTime = DateTime.Now,
                    UpdatedDateTime  = DateTime.Now,
                };

                var password = $"{data.LastName.ToProperCase()}{r}!";
                var result   = await _userManager.CreateAsync(user, password);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, "Teacher");

                    var teacher = await _manager.AddAsync(new SchoolTeacher()
                    {
                        FirstName  = data.FirstName,
                        MiddleName = data.MiddleName,
                        LastName   = data.LastName,
                        Position   = data.Position,
                        User       = user
                    });

                    data.Id = teacher.Id;
                    await trans.CommitAsync();
                }
            }

            return(ResponseResult <SchoolTeacherViewModel> .SetSuccess(data));
        }
        public async Task <IActionResult> Delete([FromRoute] Guid id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            SchoolUser deletedEntity = await _SchoolUserRepository.Delete(id);

            if (deletedEntity == null)
            {
                return(NotFound());
            }
            return(Ok(deletedEntity));
        }
Ejemplo n.º 19
0
 public async Task <SchoolUser> Add(SchoolUser entity)
 {
     //_oefenplatformContext.Add(entity);
     _oefenplatformContext.Set <SchoolUser>().Add(entity); //Use this Set or just Add?
     try
     {
         await _oefenplatformContext.SaveChangesAsync();
     }
     catch
     {
         Console.WriteLine("Test failed");
         return(null); //tests resolve into this
     }
     return(entity);
 }
        public List <StudentViewModel> GetStudents(SchoolUser user)
        {
            IList <StudentProfile> students = _manager.GetList(o => o.School.Id == user.School.Id && o.DeletedDateTime == null, o => o.School, o => o.User, o => o.Records);
            var currentSchoolYear           = _sy.GetCurrentSchoolYear(user.School.Id);

            switch (user.Type)
            {
            case UserType.Admin:

                break;

            case UserType.Clerk:

                break;

            case UserType.Teacher:
                var adviser = _teacherManager.GetSingle(o => o.User.Id == user.Id, o => o.User);
                var records = _records.GetStudentRecords(adviser.Id, currentSchoolYear.Id);
                students = students.Where(o => o.Records.Select(i => i.Id).Intersect(records.Select(i => i.Id)).Any()).ToList();

                break;

            case UserType.Parent:
                students = new List <StudentProfile>();
                break;

            case UserType.Student:
                students = new List <StudentProfile>();
                break;
            }


            return(students.Select(o => new StudentViewModel()
            {
                Id = o.Id,
                DOB = o.DOB,
                Email = o.Email,
                FirstName = o.FirstName,
                LastName = o.LastName,
                MiddleName = o.MiddleName,
                Gender = o.Gender,
                Mobile = o.Mobile,
                Phone = o.Phone,
                SchoolId = o.School.Id,
                StudentId = o.StudentId,
                UserId = Guid.Parse(o.User.Id)
            }).ToList());
        }
        private async Task LoadSharedKeyAndQrCodeUriAsync(SchoolUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
        public async Task <IActionResult> Put([FromRoute] Guid id, [FromBody] SchoolUser entity)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (id != entity.Id)
            {
                return(BadRequest());
            }

            SchoolUser updatedEntity = await _SchoolUserRepository.Update(entity);

            if (updatedEntity == null)
            {
                return(NotFound());
            }
            return(Ok(updatedEntity));
        }
Ejemplo n.º 23
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new SchoolUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

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

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Ejemplo n.º 24
0
        // the names of its parameters must be the same as the property of the User class if we use asp-for in the view
        // otherwise form values won't be passed properly
        public async Task <IActionResult> Edit(string id, string userName, string email)
        {
            SchoolUser user = await userManager.FindByIdAsync(id);

            if (user != null)
            {
                // Validate UserName and Email
                user.UserName = userName; // UserName won't be changed in the database until UpdateAsync is executed successfully
                user.Email    = email;
                IdentityResult validUseResult = await userValidator.ValidateAsync(userManager, user);

                if (!validUseResult.Succeeded)
                {
                    AddErrors(validUseResult);
                }

                // Update user info
                if (validUseResult.Succeeded)
                {
                    // UpdateAsync validates user info such as UserName and Email except password since it's been hashed
                    IdentityResult result = await userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Index", "SuperAdmin"));
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "User Not Found");
            }
            ;

            return(View(user));
        }
Ejemplo n.º 25
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new SchoolUser {
                    UserName = Input.Email, Email = Input.Email, FirstName = Input.FirstName, LastName = Input.LastName, SchoolNumber = Input.SchoolNo, City = Input.City
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Ejemplo n.º 26
0
        public async Task <IActionResult> Delete(string id)
        {
            SchoolUser user = await userManager.FindByIdAsync(id);

            if (user != null)
            {
                IdentityResult result = await userManager.DeleteAsync(user);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    AddErrors(result);
                }
            }
            else
            {
                ModelState.AddModelError("", "User Not Found");
            }

            return(View("Index", userManager.Users));
        }
Ejemplo n.º 27
0
        private static UserContext CreateUserContext(SchoolUser schoolUser, Data.School.Model.SchoolYear schoolYear = null)
        {
            int roleId;

            int personId = schoolUser.User.IsDemoUser
                ? DemoPersonService.GetPersonDataForLogin(schoolUser.User, out roleId)
                : PersonDataAccess.GetPersonDataForLogin(schoolUser.User.District.ServerUrl,
                                                         schoolUser.DistrictRef, schoolUser.UserRef, out roleId);
            var user   = schoolUser.User;
            var school = schoolUser.School;
            var role   = CoreRoles.GetById(roleId);

            Guid?developerId = null;

            if (schoolUser.User.IsDemoUser)
            {
                var developer = CreateMasterSysAdmin().UserService.GetById(user.District.Id);
                if (developer != null)
                {
                    developerId = developer.Id;
                }
            }
            return(new UserContext(user, role, user.District, school, developerId, personId, null, schoolYear));
        }
        private bool Validate(StudentViewModel data, SchoolUser user)
        {
            var IsValid = true;

            var st = _student.GetStudents(user.School.Id);

            foreach (var s in st.Where(o => o.Id != data.Id))
            {
                if (data.FullName.Trim() == s.FullName.Trim() && data.DOB == s.DOB)
                {
                    AddPageAlerts(PageAlertType.Warning, "This student already exist!");
                    IsValid = false;
                    break;
                }
                if ((DateTime.Now.Year - data.DOB.Year) < 2)
                {
                    AddPageAlerts(PageAlertType.Warning, "This student is too young to go to school!");
                    IsValid = false;
                    break;
                }
            }

            return(IsValid);
        }
Ejemplo n.º 29
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/Home/Lessons");
            if (ModelState.IsValid)
            {
                var user = new SchoolUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, "کاربر");

                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            return(Page());
        }
Ejemplo n.º 30
0
 public void ClearUser()
 {
     CurrentUser = new SchoolUser();
     Counter     = 0;
     NotifyPropertyChanged();
 }