예제 #1
0
        public async Task <IActionResult> Login([FromBody] BackOfficeLoginViewModel model)
        {
            User user = await DataContext.Store.GetOneAsync <User>(u => u.UserName.ToLower() == model.Username.ToLower());

            if (user == null)
            {
                return(NotFound());
            }
            if (!(await UserManager.IsInRoleAsync(user, UserRoles.Administrator.ToString())))
            {
                return(Unauthorized());
            }

            bool valid = await UserManager.CheckPasswordAsync(user, model.Password);

            if (!valid)
            {
                return(Unauthorized());
            }

            return(Ok(new AccessTokenModel()
            {
                AccessToken = await JwtFactory.GenerateToken(user)
            }));
        }
예제 #2
0
        public async Task <IActionResult> Register(AgentRegistrationViewModel model)
        {
            User user = Mapper.Map <User>(model);

            IdentityResult result = await UserManager.CreateAsync(user);

            if (!result.Succeeded)
            {
                return(new BadRequestObjectResult(result.Errors));
            }

            result = await UserManager.AddToRoleAsync(user, UserRoles.Agent.ToString());

            if (!result.Succeeded)
            {
                return(new BadRequestObjectResult(result.Errors));
            }

            result = await UserManager.AddPasswordAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(new BadRequestObjectResult(result.Errors));
            }

            user.MajorRole = UserRoles.Agent;
            await user.InitializeAsync();

            return(Ok(new AccessTokenModel()
            {
                AccessToken = await JwtFactory.GenerateToken(user)
            }));
        }
예제 #3
0
        public async Task <IActionResult> Login([FromBody] LoginViewModel model)
        {
            User user = null;

            if (model.Username.IsEmailAddress())
            {
                user = await UserManager.FindByEmailAsync(model.Username);
            }
            if (user == null)
            {
                user = await UserManager.FindByNameAsync(model.Username);
            }

            if (user == null)
            {
                return(NotFound());
            }

            if (!await UserManager.CheckPasswordAsync(user, model.Password))
            {
                return(Unauthorized());
            }

            return(Ok(new AccessTokenModel()
            {
                AccessToken = await JwtFactory.GenerateToken(user)
            }));
        }
예제 #4
0
        public async Task <IActionResult> ResetPassword(OneTimePasswordResetViewModel model)
        {
            User user = await UserManager.FindByNameAsync(model.Username);

            if (user == null)
            {
                return(NotFound($"No username ({model.Username}) could be found on this platform"));
            }

            bool success = await Auth.ValidateOneTimePassword(user, OnePasswordType.Phone, model.OneTimePassword);

            if (!success)
            {
                return(BadRequest("The provided one time password is expired or invalid"));
            }

            string token = await UserManager.GeneratePasswordResetTokenAsync(user);

            await UserManager.ResetPasswordAsync(user, token, model.NewPassword);

            return(Ok(new AccessTokenModel()
            {
                AccessToken = await JwtFactory.GenerateToken(user)
            }));
        }
예제 #5
0
        public async Task <IActionResult> ResetPassword(PasswordResetViewModel model)
        {
            User user = await UserManager.FindByNameAsync(model.Username);

            if (user == null)
            {
                return(NotFound($"No username ({model.Username}) could be found on this platform"));
            }

            bool success = (await UserManager.
                            ResetPasswordAsync(user, model.Token, model.NewPassword)).Succeeded;

            if (!success)
            {
                success = (await UserManager.
                           ResetPasswordAsync(user, HttpUtility.UrlDecode(model.Token),
                                              model.NewPassword)).Succeeded;
            }

            if (!success)
            {
                return(BadRequest("The provided token is expired or invalid"));
            }

            return(Ok(new AccessTokenModel()
            {
                AccessToken = await JwtFactory.GenerateToken(user)
            }));
        }
예제 #6
0
        public async Task <IActionResult> Register([FromBody] UserRegistrationViewModel model)
        {
            User user = Mapper.Map <User>(model);

            IdentityResult result = await UserManager.CreateAsync(user);

            if (!result.Succeeded)
            {
                return(new BadRequestObjectResult(result.Errors));
            }

            result = await UserManager.AddToRoleAsync(user, UserRoles.Regular.ToString());

            if (!result.Succeeded)
            {
                return(new BadRequestObjectResult(result.Errors));
            }

            result = await UserManager.AddPasswordAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(new BadRequestObjectResult(result.Errors));
            }

            await user.InitializeAsync();

            try
            {
                string template = await EmailService.GetTemplateAsync(Core.EmailTemplates.Verification);

                template = template.Replace("|USERNAME|", user.FirstName);
                await EmailService.SendEmailAsync(user.Email, "Welcome To Chop9ja", template);
            }
            catch (Exception ex)
            {
                Logger.LogError($"An error occured while sending an welcome email\n{ex}");
            }


            string message = string.Format("Hello {0}\n Welcome to Chop9ja. Click on the link below to validate your account", user.FirstName);
            await SmsService.SendMessage(user.FormattedPhoneNumber, message);

            return(Ok(new AccessTokenModel()
            {
                AccessToken = await JwtFactory.GenerateToken(user)
            }));
        }
        private async Task <string> GenerateToken(ApplicationUser user)
        {
            var claims = new List <Claim>()
            {
                new Claim("Id", user.Id.ToString()),
                new Claim("Name", $"{user.FirstName} {user.LastName}"),
                new Claim("Email", user.Email),
                new Claim("PictureURL", user.PictureUrl),
                new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
                new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()),
            };

            var roleNames = await _userManager.GetRolesAsync(user);

            foreach (var roleName in roleNames)
            {
                var roleClaim = new Claim(ClaimTypes.Role, roleName);
                claims.Add(roleClaim);
            }

            return(_jwtFactory.GenerateToken(claims));
        }
예제 #8
0
        public async Task Should_ReturnJwtToken_WhenUser_Provided()
        {
            // Arrange
            var options = Options.Create(new JwtIssuerOptions());

            var userMock = new Mock <ApplicationUser>();

            // needed for non virtual property
            userMock.SetupAllProperties();
            userMock.Object.FirstName = "Test";

            // asp.net user virtual properties
            userMock.Setup(m => m.Id).Returns("001");
            userMock.Setup(m => m.Email).Returns("*****@*****.**");
            userMock.Setup(m => m.UserName).Returns("*****@*****.**");

            var sut = new JwtFactory(options);

            // Act
            var token = await sut.GenerateToken(userMock.Object);

            // Assert
            token.ShouldNotBeNull();
        }