public async Task <ActionResult> Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                var userDto = new UserCredentialsDTO {
                    UserName = model.UserName, Password = model.Password
                };
                //var userDto = _mapper.Map<UserCredentialsDTO>(model);
                ClaimsIdentity claim = await UserService.Authenticate(userDto);

                if (claim == null)
                {
                    ModelState.AddModelError("", "Неверный логин или пароль.");
                }
                else
                {
                    AuthManager.SignOut();
                    AuthManager.SignIn(new AuthenticationProperties
                    {
                        IsPersistent = true
                    }, claim);
                    return(RedirectToAction("Index", "Home"));
                }
            }
            return(View(model));
        }
        public async Task <IActionResult> Login([FromBody] UserCredentialsDTO userCredentialsDTO)
        {
            if (userCredentialsDTO == null)
            {
                return(BadRequest(PearUp.Constants.CommonErrorMessages.Request_Is_Not_Valid));
            }
            var user = await _authenticationService.Authenticate(userCredentialsDTO.PhoneNumber, userCredentialsDTO.Password);

            if (!user.IsSuccessed)
            {
                return(BadRequest(user.GetErrorString()));
            }

            var token = CreateUserToken(user.Value);

            if (!token.IsSuccessed)
            {
                return(BadRequest(token.GetErrorString()));
            }
            var response = new LoginResponseDTO
            {
                Token = token.Value.Value,
            };

            return(Ok(response));
        }
        public async Task <ActionResult> Register(RegisterUserModel model)
        {
            // default role
            var defaultRoleName = "User";

            //await SetInitialDataAsync();
            if (ModelState.IsValid)
            {
                var userDto = new UserCredentialsDTO
                {
                    Email    = model.Email,
                    Password = model.Password,
                    UserName = model.UserName,
                    Role     = defaultRoleName
                };
                var profileDto = new UserProfileDTO
                {
                    JoinDate  = model.JoinDate,
                    BirthDate = model.BirthDate,
                    Location  = model.Location
                };
                OperationDetails operationDetails = await UserService.Create(userDto, profileDto);

                if (operationDetails.Succeeded)
                {
                    return(View("RegisterSuccess"));
                }
                else
                {
                    ModelState.AddModelError(operationDetails.Error.PropertyName, operationDetails.Error.DescriptionMessage);
                }
            }
            return(View(model));
        }
        public IActionResult Login(UserCredentialsDTO credentials)
        {
            if (!IsCredentialsObjectValid(credentials))
            {
                return(BadRequest());
            }

            var user = _userService.GetAll().FirstOrDefault(x => x.Name == credentials.Username);

            if (user == null)
            {
                return(new NotFoundResult());
            }

            if (!string.IsNullOrWhiteSpace(user.HashedPassword))
            {
                //TODO: Hash the supplied password and compared it hashed password on the user object
            }

            var token =
                _tokenService.BuildToken(
                    _config["Jwt:Key"].ToString(),
                    _config["Jwt:Issuer"].ToString(),
                    user);

            return(new ContentResult {
                Content = token, StatusCode = 200
            });
        }
Example #5
0
        public async Task <AuthResponseDTO> Login(UserCredentialsDTO dto)
        {
            ValidationResult result = _credentialsValidator.Validate(dto);

            if (result.Errors.Count > 0)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest, result.Errors);
            }
            User userExist = await _repository.GetByEmail(dto.Email);

            if (userExist == null)
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized, new
                {
                    Message = "Usuário/senha inválido(s)"
                });
            }
            bool password = BCrypt.Net.BCrypt.Verify(dto.Password, userExist.Password);

            if (!password)
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized, new
                {
                    Message = "Usuário/senha inválido(s)"
                });
            }
            var token = _tokenService.GenerateToken(userExist);

            userExist.Password = null;
            return(new AuthResponseDTO {
                Token = token,
                User = _mapper.Map <UserDTO>(userExist)
            });
        }
Example #6
0
        public async Task Login_Should_Return_AuthenticationToken_When_Credentials_Are_Valid()
        {
            var userServiceMock   = new Mock <IPearUpAuthenticationService>();
            var tokenProviderMock = new Mock <ITokenProvider>();
            var userLoginDTO      = new UserCredentialsDTO
            {
                PhoneNumber = "9999999999",
                Password    = "******"
            };

            var user = await Builders.UserBuilder.Builder().BuildAsync();

            var authTokenMock = new Mock <IAuthToken>();

            authTokenMock.Setup(a => a.Value).Returns(VALID_AUTH_TOKEN);

            userServiceMock.Setup(us => us.Authenticate(userLoginDTO.PhoneNumber, userLoginDTO.Password)).ReturnsAsync(Result.Ok(user));
            tokenProviderMock.Setup(tp => tp.CreateToken(It.IsAny <TokenInfo>(), It.IsAny <bool>())).Returns(Result.Ok(authTokenMock.Object));
            var controller = new AuthenticationController(userServiceMock.Object, tokenProviderMock.Object);

            var actualResult = await controller.Login(userLoginDTO);

            Assert.IsAssignableFrom <OkObjectResult>(actualResult);
            var contentResult = actualResult as OkObjectResult;

            Assert.AreEqual(200, contentResult.StatusCode.Value);
            Assert.IsAssignableFrom <LoginResponseDTO>(contentResult.Value);
            var actualValue = contentResult.Value as LoginResponseDTO;

            Assert.AreEqual(VALID_AUTH_TOKEN, actualValue.Token);
        }
Example #7
0
        public async Task <IActionResult> Login(UserCredentialsDTO userCredentials)
        {
            if (ModelState.IsValid)
            {
                OutputHandler   resultHandler   = new OutputHandler();
                PersonalDetails personalDetails = new PersonalDetails();
                var             requestUrl      = $"{BaseUrl}{apiUri}/Login";
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(requestUrl);
                    client.DefaultRequestHeaders.Accept.Clear();
                    var result = await client.PostAsJsonAsync(client.BaseAddress, userCredentials);

                    if (result.StatusCode == HttpStatusCode.OK)
                    {
                        personalDetails = await result.Content.ReadAsAsync <PersonalDetails>();

                        if (personalDetails != null)
                        {
                            ViewBag.role = personalDetails.RoleId;
                            HttpContext.Session.SetString(SessionUserName, personalDetails.EmailAddress);
                            HttpContext.Session.SetInt32(SessionKeyRole, personalDetails.RoleId);
                            //get position abbr and name later
                            return(RedirectToAction("Index", "Home", new { roleid = personalDetails.RoleId, user = personalDetails.EmailAddress }));
                        }
                        else
                        {
                            var userDTO = new UserCredentialsDTO
                            {
                                Message        = "Account not found, Check your password or username and try again.",
                                IsErrorOccured = true
                            };

                            return(View(userDTO));
                        }
                    }
                    else if (result.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        var userDTO = new UserCredentialsDTO
                        {
                            Message        = "Login failed,Check your password and username and try again",
                            IsErrorOccured = true
                        };

                        return(View(userDTO));
                    }
                    else
                    {
                        var userDTO = new UserCredentialsDTO
                        {
                            Message        = "Something went wrong, Check you credentials and try again",
                            IsErrorOccured = true
                        };

                        return(View(userDTO));
                    }
                };
            }
            return(View());
        }
Example #8
0
        public async Task <UserSignedDTO> Post(UserCredentialsDTO credentials)
        {
            credentials.Token = JwtTokenHelper.GenerateToken(credentials.Email);

            return(await ExecuteAsync(
                       () => userFacade.SignInUser(credentials),
                       (ex) => throw new UnauthorizedException(ex)));
        }
Example #9
0
        public IActionResult Login()
        {
            var viewModel = new UserCredentialsDTO
            {
                IsErrorOccured = false
            };

            return(View(viewModel));
        }
        public async Task <ClaimsIdentity> Authenticate(UserCredentialsDTO userDto)
        {
            ClaimsIdentity claim = null;
            var            user  = await _db.UserManager.FindAsync(userDto.UserName, userDto.Password);

            if (user != null)
            {
                claim = await _db.UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            }
            return(claim);
        }
Example #11
0
        public IActionResult Register([FromBody] UserCredentialsDTO userCredentials)
        {
            var user = _mapper.Map <User>(userCredentials);

            var createdUser = _userService.Create(user, userCredentials.Password);

            var userDTO = _mapper.Map <UserDTO>(createdUser);

            userDTO.Token = _userTokenService.CreateToken(createdUser);
            return(Ok(userDTO));
        }
Example #12
0
        public async Task <IActionResult> Login([FromBody] UserCredentialsDTO userCredentialsDTO)
        {
            ApiResponse <LoginResponse> apiResponse = new ApiResponse <LoginResponse>();

            try
            {
                ValidateSignInResult validateSignInResult = await this._authenticationService.ValidateSignInAsync(userCredentialsDTO.Email, userCredentialsDTO.Password);

                if (validateSignInResult.State != ValidateSignInState.Success)
                {
                    apiResponse.Error   = true;
                    apiResponse.Message = validateSignInResult.State.Switch(new Dictionary <ValidateSignInState, Func <string> >()
                    {
                        { ValidateSignInState.NotFound, () => Resource_ResponseMessages_en.UserNotFound },
                        { ValidateSignInState.WrongPassword, () => Resource_ResponseMessages_en.WrongPassword }
                    },
                                                                            () => Resource_ResponseMessages_en.Unknown
                                                                            );

                    return(BadRequest(apiResponse));
                }

                validateSignInResult.User.Ipv4 = HttpUtils.GetUserIp(HttpContext);

                // Do not await in order to respond as fast as possible,
                // the task completion is not necessary for the response creation.
                _ = _auditLogStore.CreateLogAsync(new AuditLog()
                {
                    UserId      = validateSignInResult.User.Id,
                    EventTypeId = EventTypeId.Login,
                    IPv4        = validateSignInResult.User.Ipv4
                });

                apiResponse.Message        = Resource_ResponseMessages_en.LoginSuccess;
                apiResponse.EndpointResult = new LoginResponse(this._jWTService.Generate(validateSignInResult.User));

                return(Ok(apiResponse));
            }
            catch (DbException e)
            {
                apiResponse.Error   = true;
                apiResponse.Message = Resource_ResponseMessages_en.Unknown;
                // TODO: Error handling.
                return(Problem(statusCode: 500, detail: Newtonsoft.Json.JsonConvert.SerializeObject(e, Newtonsoft.Json.Formatting.Indented)));
            }
            catch (Exception e)
            {
                apiResponse.Error   = true;
                apiResponse.Message = Resource_ResponseMessages_en.Unknown;
                // TODO: Error handling.
                return(Problem(statusCode: 500, detail: Newtonsoft.Json.JsonConvert.SerializeObject(e, Newtonsoft.Json.Formatting.Indented)));
            }
        }
Example #13
0
        public IActionResult Authentificate([FromBody] UserCredentialsDTO userCredentials)
        {
            var response = this.authService.AuthentificateUser(userCredentials);

            if (response.Ok)
            {
                return(Ok(response.Data));
            }
            else
            {
                return(BadRequest(response.Message));
            }
        }
Example #14
0
        public async Task <IActionResult> Register([FromBody] UserCredentialsDTO userCredentialsDTO)
        {
            ApiResponse <LoginResponse> apiResponse = new ApiResponse <LoginResponse>();

            try
            {
                IAppUser newAppUser = new AppUser()
                {
                    Email    = userCredentialsDTO.Email,
                    Password = userCredentialsDTO.Password,
                    Ipv4     = HttpUtils.GetUserIp(HttpContext)
                };

                RegisterUserResult registerUserResult = await this._authenticationService.RegisterUserAsync(newAppUser);

                if (registerUserResult.State != RegisterUserState.Success)
                {
                    apiResponse.Error   = true;
                    apiResponse.Message = registerUserResult.State.Switch(new Dictionary <RegisterUserState, Func <string> >()
                    {
                        { RegisterUserState.EmailExists, () => Resource_ResponseMessages_en.EmailExists },
                        { RegisterUserState.PasswordTooSmall, () => Resource_ResponseMessages_en.PasswordTooSmall },
                        { RegisterUserState.InvalidEmail, () => Resource_ResponseMessages_en.InvalidEmail }
                    },
                                                                          () => Resource_ResponseMessages_en.Unknown
                                                                          );

                    return(BadRequest(apiResponse));
                }

                apiResponse.Message        = Resource_ResponseMessages_en.RegisterSuccess;
                apiResponse.EndpointResult = new LoginResponse(this._jWTService.Generate(newAppUser));

                return(Ok(apiResponse));
            }
            catch (DbException e)
            {
                apiResponse.Error   = true;
                apiResponse.Message = Resource_ResponseMessages_en.Unknown;
                // TODO: Error handling.
                return(Problem(statusCode: 500, detail: Newtonsoft.Json.JsonConvert.SerializeObject(e, Newtonsoft.Json.Formatting.Indented)));
            }
            catch (Exception e)
            {
                apiResponse.Error   = true;
                apiResponse.Message = Resource_ResponseMessages_en.Unknown;
                // TODO: Error handling.
                return(Problem(statusCode: 500, detail: Newtonsoft.Json.JsonConvert.SerializeObject(e, Newtonsoft.Json.Formatting.Indented)));
            }
        }
Example #15
0
        public async Task <LoggedInUserDTO> LoginAsync(UserCredentialsDTO credentialsDTO)
        {
            string passwordHash = ConverterSuit.ByteArrayToHex(HashSuit.ComputeSha256(Encoding.UTF8.GetBytes(credentialsDTO.Password)));
            User   user         = await authRepository.LoginAsync(credentialsDTO.UserId, passwordHash);

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

            LoggedInUserDTO loggedInUser = mapper.Map <LoggedInUserDTO>(user);

            loggedInUser.JwtToken = jwtSuit.GetToken(user);
            return(loggedInUser);
        }
Example #16
0
        public IActionResult Authenticate([FromBody] UserCredentialsDTO userCredentials)
        {
            var user = _userService.Authenticate(userCredentials.Username,
                                                 userCredentials.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            var userDTO = _mapper.Map <UserDTO>(user);

            userDTO.Token = _userTokenService.CreateToken(user);
            return(Ok(userDTO));
        }
        public async Task <IActionResult> Login([FromBody] UserCredentialsDTO userCredentialsDTO)
        {
            UserInfoDTO userInfoDTO = await authService.LoginAsync(userCredentialsDTO);

            if (userInfoDTO == null)
            {
                return(BadRequest(new BadResponseDTO {
                    Status = (int)400, Errors = new Errors {
                        Message = new List <string> {
                            "Credentials are wrong"
                        }
                    }
                }));
            }
            return(Ok(userInfoDTO));
        }
Example #18
0
        public async Task <ActionResult <TokenDTO> > CreateUser([FromBody] UserCredentialsDTO userCredentialsDTO)
        {
            var user = new IdentityUser {
                UserName = userCredentialsDTO.EmailAddress, Email = userCredentialsDTO.EmailAddress
            };
            var result = await _userManager.CreateAsync(user, userCredentialsDTO.Password);

            if (result.Succeeded)
            {
                return(await BuildToken(userCredentialsDTO));
            }
            else
            {
                return(BadRequest(result.Errors));
            }
        }
Example #19
0
        public async Task <ActionResult <TokenDTO> > Login([FromBody] UserCredentialsDTO userCredentialsDTO)
        {
            var result = await _signInManager.PasswordSignInAsync(
                userCredentialsDTO.EmailAddress,
                userCredentialsDTO.Password,
                isPersistent : false,
                lockoutOnFailure : false);

            if (result.Succeeded)
            {
                return(await BuildToken(userCredentialsDTO));
            }
            else
            {
                return(BadRequest("Invalid Login attempt"));
            }
        }
Example #20
0
        public ApiResponse <User> AuthentificateUser(UserCredentialsDTO userCredentials)
        {
            var user = this.userRepo.GetByEmail(userCredentials.Email).Result;

            if (user == null)
            {
                return(BuildApiResponse.BuildNotOk <User>(null, "Email no registrado en el sistema"));
            }
            else if (user.Email == userCredentials.Email && user.Password == userCredentials.Password)
            {
                return(BuildApiResponse.BuildOk <User>(user));
            }
            else
            {
                return(BuildApiResponse.BuildNotOk <User>(null, "Email o Password incorrecto"));
            }
        }
Example #21
0
        public HttpResponseMessage Login(UserCredentialsDTO Credentials)
        {
            try
            {
                string identifier     = Credentials.Identifier;
                SHA512 SHA            = new SHA512Managed();
                string password       = Credentials.Password;
                var    password_bytes = ASCIIEncoding.ASCII.GetBytes(password);
                byte[] passBytes      = new byte[password_bytes.Length];
                for (int i = 0; i < password_bytes.Length; i++)
                {
                    passBytes[i] = password_bytes[i];
                }
                string hashedPass = Convert.ToBase64String(SHA.ComputeHash(passBytes));
                using (var context = new AcademicSystemContext())
                {
                    var user = context.Usuarios.Where(u => (u.UserId.ToString() == identifier || u.Email == identifier) && u.Password == hashedPass).FirstOrDefault();


                    if (user != null)
                    {
                        var cookie = new HttpCookie("appUser", identifier + "," + password);
                        cookie.HttpOnly = true;
                        HttpContext.Current.Response.Cookies.Add(cookie);
                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }

                    else
                    {
                        return(Request.CreateResponse(HttpStatusCode.Unauthorized));
                    }
                }
            }
            catch (Exception e)
            {
                EmailSender s = new EmailSender();
                s.SendEmail(e.Message + " fin mesage" + e.StackTrace + e.Source, "error", "*****@*****.**", false);
                if (e.InnerException != null)
                {
                    s.SendEmail(e.InnerException.Message + "INNER", "error", "*****@*****.**", false);
                }
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
Example #22
0
        public string Login(UserCredentialsDTO credentials)
        {
            //TODO: get from DB
            var validLogin    = _configuration["HardcodedLogin"] == credentials.Login;
            var validPassword = _configuration["HardcodedPassword"] == credentials.Password;

            if (validLogin && validPassword)
            {
                var claims = new List <Claim>()
                {
                    new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString(), ClaimValueTypes.Integer64)
                };

                return(GenerateToken(claims, DateTime.Now.AddHours(TOKEN_EXPIRATION_FOR_USER_HOURS)));
            }
            else
            {
                throw new CredentialsException();
            }
        }
Example #23
0
        /// <summary>
        /// Signs user in
        /// </summary>
        /// <param name="credentials">User credentials</param>
        /// <returns>Information about signed user</returns>
        /// <exception cref="BLException">Throw when user credentials are invalid</exception>
        public async Task <UserSignedDTO> SignInUser(UserCredentialsDTO credentials)
        {
            using var uow = UowProviderFunc().Create();
            var repo = userRepositoryFunc();
            var user = await repo.GetByEmailAsync(credentials.Email);

            if (user == null || !SecurityHelper.VerifyHashedPassword(user.PasswordHash, user.PasswordSalt, credentials.Password))
            {
                throw new BLException(UserErrorCode.InvalidCredentials, ErrorMessages.InvalidCredentials);
            }

            user.LastLoginOn = DateTime.Now;
            user.TokenHash   = Convert.ToBase64String(SecurityHelper.CreateHash(user.PasswordSalt, credentials.Token));
            await uow.CommitAsync();

            var result = mapper.Map <UserSignedDTO>(user);

            result.Token = credentials.Token;
            return(result);
        }
Example #24
0
        public async Task Login_Should_Return_ErrorMessage_When_Credentials_Are_Empty()
        {
            var userServiceMock = new Mock <IPearUpAuthenticationService>();
            var failureResult   = Result.Fail <User>(Constants.UserErrorMessages.Phone_Number_And_Password_Are_Required);

            userServiceMock.Setup(us => us.Authenticate(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(failureResult);
            var controller   = new AuthenticationController(userServiceMock.Object, null);
            var userLoginDTO = new UserCredentialsDTO
            {
                PhoneNumber = "",
                Password    = ""
            };
            var actualResult = await controller.Login(userLoginDTO);

            Assert.IsAssignableFrom <BadRequestObjectResult>(actualResult);
            var contentResult = actualResult as BadRequestObjectResult;

            Assert.AreEqual(400, contentResult.StatusCode.Value);
            Assert.IsAssignableFrom <string>(contentResult.Value);
            Assert.AreEqual(Constants.UserErrorMessages.Phone_Number_And_Password_Are_Required, contentResult.Value);
        }
        public async Task <OperationDetails> Create(UserCredentialsDTO user, UserProfileDTO profileDto)
        {
            var usr = await _db.UserManager.FindByEmailAsync(user.Email);//.CreateAsync(_mapper.Map<ApplicationUser>(user));

            if (usr == null)
            {
                usr = await _db.UserManager.FindByNameAsync(user.UserName);
            }
            else
            {
                return(new OperationDetails(new OperationFailureError("This email is already taken", "Email")));
            }
            if (usr == null)
            {
                var usrCredentials = _mapper.Map <ApplicationUser>(user);
                // OR NEED TO CREATE IMPLICITLY !!!! IMPORTANT!!!
                // = new ApplicationUser() { UserName = ... }
                var result = await _db.UserManager.CreateAsync(usrCredentials, user.Password);

                if (result.Errors.Count() > 0)
                {
                    return(new OperationDetails(new OperationFailureError(result.Errors.FirstOrDefault(), "")));
                }

                await _db.UserManager.AddToRoleAsync(usrCredentials.Id, user.Role);

                // create profile
                var profile = _mapper.Map <UserProfile>(profileDto);
                profile.Id = usrCredentials.Id;
                _db.Profiles.Create(profile);
                await _db.SaveAsync();

                return(new OperationDetails());
            }
            else
            {
                return(new OperationDetails(new OperationFailureError("This username is already taken", "UserName")));
            }
        }
Example #26
0
        public static string BuildToken(UserCredentialsDTO userCredentials, Config config)
        {
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, userCredentials.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Role, userCredentials.UserRole.ToString())
            };

            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.Key));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                claims: claims,
                issuer:  config.Issuer,
                audience: config.Issuer,
                expires: DateTime.Now.AddMonths(1),
                signingCredentials: credentials
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Example #27
0
        public IActionResult Login(UserCredentialsDTO userCredentialsDTO)
        {
            if (userCredentialsDTO == null)
            {
                throw new ArgumentException("Credentials are missing");
            }

            bool uowStatus = false;

            try
            {
                Specification <Employee> specification = GetLogingSpecification(userCredentialsDTO.Username, userCredentialsDTO.Password);
                uowStatus = _unitOfWork.BeginTransaction();
                List <Employee> employees = _securityRepository.GetList(specification);
                _unitOfWork.Commit(uowStatus);

                if (employees.FirstOrDefault() == null)
                {
                    throw new ArgumentException("Employee is not logged in");
                }

                EmployeeDto employeeDto = _empleadoLoginAssembler.toDto(employees.FirstOrDefault());
                var         token       = Token.GenerateToken(employeeDto.Username);
                return(Ok(responseHandler.getOkCommandResponse("bearer " + token, Constants.HttpStatus.Success, employeeDto)));
            }
            catch (ArgumentException ex)
            {
                _unitOfWork.Rollback(uowStatus);
                Console.WriteLine(ex.StackTrace);
                return(Unauthorized());
            }
            catch (Exception ex)
            {
                _unitOfWork.Rollback(uowStatus);
                Console.WriteLine(ex.StackTrace);
                return(StatusCode(StatusCodes.Status500InternalServerError, responseHandler.getAppExceptionResponse()));
            }
        }
Example #28
0
        private async Task <TokenDTO> BuildToken(UserCredentialsDTO userCredentialsDTO)
        {
            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, userCredentialsDTO.EmailAddress),
                new Claim(ClaimTypes.Email, userCredentialsDTO.EmailAddress)
            };

            var user = await _userManager.FindByEmailAsync(userCredentialsDTO.EmailAddress);

            var userRoles = (List <string>) await _userManager.GetRolesAsync(user);

            foreach (var role in userRoles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["jwt:secret"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var expirey = DateTime.UtcNow.AddHours(1);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: null,
                audience: null,
                claims: claims,
                expires: expirey,
                signingCredentials: creds
                );

            return(new TokenDTO()
            {
                Token = new JwtSecurityTokenHandler().WriteToken(token),
                Expirey = expirey
            });
        }
 private void LoadUserData(UserCredentialsDTO obj)
 {
     UserProperty = obj.User;
 }
 private bool IsCredentialsObjectValid(UserCredentialsDTO credentials)
 {
     return(credentials != null &&
            !string.IsNullOrWhiteSpace(credentials.Username));
     //&& !string.IsNullOrWhiteSpace(credentials.Password);
 }