Ejemplo n.º 1
0
        public async Task <BaseModel <UserModel> > Login(string email, string password)
        {
            BaseModel <UserModel> result = new BaseModel <UserModel>();

            try
            {
                User user = await _users.Find(u => u.Email == email).FirstOrDefaultAsync();

                if (user != null)
                {
                    bool isVerified = VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt);

                    if (isVerified)
                    {
                        string refreshToken = _passwordHasher.HashPassword(user, Guid.NewGuid().ToString())
                                              .Replace("+", string.Empty)
                                              .Replace("=", string.Empty)
                                              .Replace("/", string.Empty);

                        UserRefreshToken userRefreshToken = new UserRefreshToken()
                        {
                            UserId       = user.Id,
                            RefreshToken = refreshToken
                        };

                        await _userRefreshTokens.InsertOneAsync(userRefreshToken);

                        result.Data = new UserModel
                        {
                            Id           = user.Id,
                            Email        = user.Email,
                            CreatedAt    = user.CreatedAt,
                            Type         = user.Type,
                            RefreshToken = refreshToken
                        };

                        string token = _jwtProvider.GenerateToken(result.Data);

                        result.Data.Token = token;
                    }
                }
            }
            catch
            {
                throw new SystemException("Something went wrong while verifiying user.");
            }

            return(result);
        }
Ejemplo n.º 2
0
        public async Task <string> CreateDev(User dev, User creatingUser) //todo log out activities by devs
        {
            using (var trans = TransactionScopeFactory.Create())
            {
                dev.Cash     = 1000000;
                dev.IsActive = true;
                dev.Salt     = BCrypt.Net.BCrypt.GenerateSalt();
                dev.Password = BCrypt.Net.BCrypt.HashPassword(dev.Password, dev.Salt);

                dev.Id = await UserRepo.CreateDeveloper(dev);

                trans.Complete();
            }
            dev = (await UserRepo.RetrieveUsersByIds(dev.Id)).First();
            return(JwtProvider.GenerateToken(dev.Username, dev.EmailAddress, RoleTypes.Dev));
        }
Ejemplo n.º 3
0
        public string CreateAccount(User user)
        {
            using (var trans = new TransactionScope(TransactionScopeOption.Required))
            {
                //TODO validate incoming properties (Birthday, gender, email, username)
                user.Cash     = 500; //TODO economics
                user.IsActive = true;
                user.Salt     = BCrypt.Net.BCrypt.GenerateSalt();
                user.Password = BCrypt.Net.BCrypt.HashPassword(user.Password, user.Salt);

                user.UserId = userRepo.CreateUser(user);

                trans.Complete();
            }
            user = RetrieveUser(user.UserId);
            return(jwtProvider.GenerateToken(user));
        }
Ejemplo n.º 4
0
 public HttpResponseMessage Authenticate(
     [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "1.0/authenticate")]
     HttpRequestMessage req)
 {
     return(ResponseBuilderHelper.BuildResponse(System.Net.HttpStatusCode.OK, new AuthenticateActivityResponse()
     {
         Token = _jwtProvider.GenerateToken(Settings.AuthorizationKey)
     }));
 }
Ejemplo n.º 5
0
        public async Task <string> CreateAccount(User user)
        {
            bool conflictFound = await UserRepo.UserExistsByUsernameOrEmail(user.Username, user.EmailAddress);

            if (conflictFound)
            {
                throw new CritterException($"Sorry, someone already exists with that name or email!", $"Duplicate account creation attempt on {user.Username} or {user.EmailAddress}", System.Net.HttpStatusCode.Conflict);
            }

            using (var trans = TransactionScopeFactory.Create())
            {
                user.Cash     = 500; //TODO economics
                user.IsActive = true;
                user.Salt     = BCrypt.Net.BCrypt.GenerateSalt();
                user.Password = BCrypt.Net.BCrypt.HashPassword(user.Password, user.Salt);

                user.Id = await UserRepo.CreateUser(user) ?? throw new CritterException("Could not create account, try again!", null, System.Net.HttpStatusCode.Conflict);

                List <int> metaphones = new List <int>();
                var        doubles    = new List <ShortDoubleMetaphone>();
                doubles.Add(new ShortDoubleMetaphone(user.Username));
                doubles.Add(new ShortDoubleMetaphone(user.FirstName));
                doubles.Add(new ShortDoubleMetaphone(user.LastName));
                doubles.ForEach(d => { metaphones.Add(d.PrimaryShortKey); metaphones.Add(d.AlternateShortKey); });
                metaphones = metaphones.Distinct().AsList();
                if (!await UserRepo.InsertMetaphone(user.Id, metaphones.ToArray()))
                {
                    Log.Logger.Error($"Failed to create metaphone for {user.Id}");
                }

                if (!await UserRepo.CreateUserMeta(user.Id, ""))
                {
                    throw new CritterException("Could not create account, try again!", $"Failed to create a user meta for user ID {user.Id}", System.Net.HttpStatusCode.InternalServerError);
                }

                trans.Complete();
            }
            user = await RetrieveUser(user.Id);

            return(JWTProvider.GenerateToken(user));
        }
Ejemplo n.º 6
0
        public TokenResponse(int userId, object role, IJwtProvider jwtProvider)
        {
            IEnumerable <Claim> claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, $"{userId}"),
                new Claim(ClaimsIdentity.DefaultRoleClaimType, $"{role}")
            };

            var claimsIdentity = new ClaimsIdentity(claims);

            Token  = jwtProvider.GenerateToken(claimsIdentity);
            UserId = claimsIdentity.Claims.GetUserId();
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> Login(UserView userView)
        {
            var user = await _userRepository.GetUserByLoginPassword(userView.Login, userView.Password);

            if (user != null)
            {
                var options = new CookieOptions
                {
                    Expires     = DateTime.Now.AddHours(8),
                    IsEssential = true
                };
                HttpContext.Response.Cookies.Append("AuthToken", _jwtProvider.GenerateToken(user), options);;
                return(RedirectToAction("Index", "Home"));
            }

            return(View("Index"));
        }
Ejemplo n.º 8
0
 public string Protect(AuthenticationTicket data, string purpose)
 {
     return(JWT.GenerateToken(data.Principal.Identity.Name, data.Principal.FindFirst(ClaimTypes.Email)?.Value));
 }
Ejemplo n.º 9
0
        public IActionResult Login([FromBody] AuthRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(StatusCode((int)HttpStatusCode.Unauthorized, new ApiResultModel <string>
                {
                    Message = "登录失败。",
                    Error = new ApiError()
                    {
                        Code = "invalid",
                        Message = "用户名或密码错误。",
                        Field = "PasswordHash",
                        Resource = "login"
                    }
                }));
            }

            var password = request.PasswordHash.DecodeBase64();

            if (string.IsNullOrEmpty(password))
            {
                return(StatusCode((int)HttpStatusCode.Unauthorized, new ApiResultModel <string>
                {
                    Message = "登录失败。",
                    Error = new ApiError()
                    {
                        Code = "invalid",
                        Message = "用户名或密码错误。",
                        Field = "PasswordHash",
                        Resource = "login"
                    }
                }));
            }

            var login = _ar.Verify(request.Username, password);

            if (login == null)
            {
                return(StatusCode((int)HttpStatusCode.Unauthorized, new ApiResultModel <string>
                {
                    Message = "登录失败。",
                    Error = new ApiError()
                    {
                        Code = "invalid",
                        Message = "用户名或密码错误。",
                        Field = "PasswordHash",
                        Resource = "login"
                    }
                }));
            }

            try
            {
                var user = _mapper.Map <UserApiViewModel>(login);
                user.Token = _jwtProvider.GenerateToken(login.Id, login.DefaultTenantId);
                return(Ok(new ApiResultModel <UserApiViewModel>
                {
                    Data = user
                }));;
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                _logger.LogError(e.StackTrace);
                return(StatusCode((int)HttpStatusCode.Unauthorized, new ApiResultModel <string>
                {
                    Message = "登录失败。",
                    Error = new ApiError()
                    {
                        Code = "invalid",
                        Message = "服务端错误。",
                        Field = "Server Error.",
                        Resource = "login"
                    }
                }));
            }
        }
Ejemplo n.º 10
0
 public string Protect(AuthenticationTicket data, string purpose)
 {
     return(jwt.GenerateToken(data.Principal.Identity.Name));
 }