Beispiel #1
0
        public async Task <User> Authenticate(AuthUserDTO authDTO)
        {
            User existingUser = await context.Users.FirstOrDefaultAsync(user => user.Phone == authDTO.Phone);

            if (existingUser == null)
            {
                return(existingUser);
            }
            bool isPasswordCorrect = BCrypt.Net.BCrypt.Verify(authDTO.Password, existingUser.Password);

            if (!isPasswordCorrect)
            {
                return(null);
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(jwtSecret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, existingUser.Phone),
                    new Claim(ClaimTypes.Role, existingUser.Role)
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            existingUser.Token = tokenHandler.WriteToken(token);
            return(existingUser.UserWithoutPassword());
        }
Beispiel #2
0
        public async Task <IActionResult> GetToken([FromBody] AuthUserDTO dto)
        {
            var identity = await GetIdentityAsync(dto.email, dto.password);

            if (identity == null)
            {
                return(Unauthorized());
            }
            var now = DateTime.UtcNow;
            // создаем JWT-токен
            var jwt = new JwtSecurityToken(
                issuer: AuthOptions.ISSUER,
                audience: AuthOptions.AUDIENCE,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)),
                signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                access_token = encodedJwt,
                username     = identity.Name
            };

            return(Ok(JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            })));
        }
        public IAuthUserDTO Login(IAuthUser authUser)
        {
            if (ValidateUser(authUser))
            {
                var(token, userId) = GenerateToken(authUser);
                return(AuthUserDTO.Create(userId, token));
            }

            throw new UnauthorizedAccessException("Usuário ou senha incorretos");
        }
Beispiel #4
0
        public async Task <IActionResult> Post([FromBody] UserRegisterDTO user)
        {
            var createdUser = await _userService.CreateUser(user);

            var token = await _authService.GenerateAccessToken(createdUser.Id, createdUser.UserName, createdUser.Email);

            var result = new AuthUserDTO
            {
                User  = createdUser,
                Token = token
            };

            return(CreatedAtAction("GetById", "users", new { id = createdUser.Id }, result));
        }
Beispiel #5
0
        public async Task <IActionResult> Post([FromBody] UserRegisterDTO user)
        {
            var createdUser = await _userService.CreateUser(user);

            var token = await _authService.GenerateAccessToken(createdUser);

            _logger.LogInformation(LoggingEvents.InsertItem, $"User created {createdUser.Id}");
            var result = new AuthUserDTO
            {
                User  = _mapper.Map <UserDTO>(createdUser),
                Token = token
            };

            return(CreatedAtAction("GetById", "users", new { id = createdUser.Id }, result));
        }
        public async Task <IActionResult> Authenticate(AuthUserDTO authDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var token = await authUserService.Authenticate(authDTO.PhoneNumber, authDTO.Code);

            if (string.IsNullOrEmpty(token))
            {
                return(Unauthorized());
            }

            return(Ok(new { token }));
        }
Beispiel #7
0
        public async Task <IHttpActionResult> Register(AuthUserDTO userModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            IdentityResult result = await _authRepo.RegisterUser(userModel);

            IHttpActionResult errorResult = GetErrorResult(result);

            if (errorResult != null)
            {
                return(errorResult);
            }

            return(Ok());
        }
Beispiel #8
0
        public async Task <IdentityResult> RegisterUser(AuthUserDTO authDTO)
        {
            IdentityUser user = new IdentityUser
            {
                UserName = authDTO.UserName
            };

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

            if (result != null && result.Succeeded)
            {
                var            roleManager  = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new KashmirFoodContext()));
                var            currUsername = _userManager.FindByName(authDTO.UserName);
                IdentityResult roleResult;
                if (roleManager.Roles.Count() == 0)
                {
                    roleManager.Create(new IdentityRole {
                        Name = "SuperAdmin"
                    });
                    roleManager.Create(new IdentityRole {
                        Name = "RestaurantOwner"
                    });
                    roleManager.Create(new IdentityRole {
                        Name = "Customer"
                    });
                }

                if (authDTO.Restaurant)
                {
                    roleResult = _userManager.AddToRole(currUsername.Id, "RestaurantOwner");
                }
                else
                {
                    roleResult = _userManager.AddToRole(currUsername.Id, "Customer");
                }
                if (roleResult != null && !roleResult.Succeeded)
                {
                    result.Errors.Union(roleResult.Errors);
                }
            }
            return(result);
        }
Beispiel #9
0
        public async Task <IActionResult> Registration([FromBody] RegistartionUserDTO registartionDTO)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest());
                }


                ResponseDTO answer = await userAuthService.Registration(registartionDTO);

                if (answer.Status == false)
                {
                    return(StatusCode(400, answer));
                }

                AuthUserDTO authDTO = new AuthUserDTO()
                {
                    Phone = registartionDTO.Phone, Password = registartionDTO.Password
                };

                User user = await userAuthService.Authenticate(authDTO);

                if (string.IsNullOrEmpty(user.Token))
                {
                    return(Unauthorized(new { status = false }));
                }

                return(Ok(new { user, answer }));
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                return(StatusCode(500, new ResponseDTO()
                {
                    Message = "На данный момент на стороне сервера ошибка, пожалуйста повторите попытку позже",
                    Status = false
                }));
            }
        }
Beispiel #10
0
        public async Task <IActionResult> Authenticate([FromBody] AuthUserDTO authDTO)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest());
                }

                User user = await userAuthService.Authenticate(authDTO);

                if (user == null)
                {
                    return(NotFound(new ResponseDTO()
                    {
                        Message = "Данный пользователь не найден", Status = false
                    }));
                }

                return(Ok(new { user }));
            }
            catch (ObjectNotFoundException ex)
            {
                logger.LogError(ex.Message);
                return(StatusCode(404, new ResponseDTO()
                {
                    Message = "Данный пользователь не найден", Status = false
                }));
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                return(StatusCode(500, new ResponseDTO()
                {
                    Message = "На данный момент на стороне сервера ошибка, пожалуйста повторите попытку позже",
                    Status = false
                }));
            }
        }
Beispiel #11
0
        private async Task Authentificate(AuthUserDTO authUserDTO)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimsIdentity.DefaultNameClaimType, authUserDTO.Id.ToString()),
                new Claim(ClaimTypes.GivenName, authUserDTO.FirstName),
                new Claim(ClaimTypes.NameIdentifier, authUserDTO.LastName),
                new Claim(ClaimTypes.Email, authUserDTO.Email)
            };

            if (authUserDTO.IsAdmin)
            {
                claims.Add(new Claim(ClaimTypes.Role, "Administrator"));
            }
            else
            {
                claims.Add(new Claim(ClaimTypes.Role, "User"));
            }

            var claimsIdentity = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
        }
        public async Task <IActionResult> Post([FromBody] UserRegisterDTO user)
        {
            var createdUser = await _userService.CreateUser(user);

            var token = await _authService.GenerateAccessToken(createdUser.Id, createdUser.UserName, createdUser.Email);

            Common.Model.User tempUser = new Common.Model.User()
            {
                Email = createdUser.Email, UserName = createdUser.UserName
            };
            var code = await _userManager.GenerateEmailConfirmationTokenAsync(tempUser);

            var callbackUrl = Url.Action(
                "ConfirmEmail",
                "Register",
                new { userId = createdUser.Id, code = code },
                protocol: HttpContext.Request.Scheme);

            try
            {
                await emailService.SendEmailAsync(createdUser.Email, "Confirm your account",
                                                  $"Подтвердите регистрацию, перейдя по ссылке: <a href='{callbackUrl}'>link</a>");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }


            var result = new AuthUserDTO
            {
                User  = createdUser,
                Token = token
            };

            return(CreatedAtAction("GetById", "users", new { id = createdUser.Id }, result));
        }
Beispiel #13
0
 public BasicAuthenticationDTO(AuthUserDTO _AuthUser) : base(_AuthUser.ToString())
 {
     _AuthUserDTO = _AuthUser;
 }