Пример #1
0
        public async Task <IActionResult> Signup(SignupRequest request)
        {
            // For a production app, it would make sense to validate
            // the format for the e-mail. E-mail technically has many
            // rules, and since we don't need to send any e-mail, we won't
            // restrict the input.

            (bool passwordValid, string error) = ValidatePassword(request.Password);
            if (!passwordValid)
            {
                return(BadRequest(error));
            }

            // Check if account already exists.
            bool accountExists = await dbContext.Users.AnyAsync(user => user.Email.Equals(request.Email, StringComparison.OrdinalIgnoreCase));

            if (accountExists)
            {
                return(BadRequest("Cannot create user! Account already exists."));
            }

            byte[] salt       = SecurityHelper.GenerateSalt();
            byte[] saltedHash = SecurityHelper.GenerateSaltedHash(Encoding.UTF8.GetBytes(request.Password), salt);

            // Create new user:
            User newUser = new User
            {
                Email              = request.Email,
                Name               = request.Name,
                AvatarUrl          = GenerateGravatarUrl(request.Email),
                Salt               = salt.ToHexString(),
                SaltedPasswordHash = saltedHash.ToHexString()
            };

            // Save the user so we can retrieve the ID.
            dbContext.Users.Add(newUser);
            await dbContext.SaveChangesAsync();


            TokenResponse response = new TokenResponse()
            {
                Token        = CreateTokenFor(newUser),
                RefreshToken = await GenerateUniqueRefreshToken()
            };

            // Remember to persist the refresh token:
            newUser.RefreshToken = response.RefreshToken;
            await dbContext.SaveChangesAsync();

            return(CreatedAtAction(nameof(GetUserInfo), response));
        }
Пример #2
0
        public async Task <ActionResult <Idea> > CreateIdea(IdeaRequest request)
        {
            // Authenticate requester.
            var jwtToken = Request.Headers["X-Access-Token"];

            if (!tokenHelper.ValidateJwtToken(jwtToken, out SecurityToken validatedToken))
            {
                return(Unauthorized());
            }

            // Sanitize inputs.
            if (request.Content.Length > 255)
            {
                return(BadRequest("Content cannot exceed 255 characters."));
            }
            if (request.Impact < 1 || request.Impact > 10)
            {
                return(BadRequest("Impact must be between 1 and 10."));
            }
            if (request.Ease < 1 || request.Ease > 10)
            {
                return(BadRequest("Ease must be between 1 and 10."));
            }
            if (request.Confidence < 1 || request.Confidence > 10)
            {
                return(BadRequest("Confidence must be between 1 and 10."));
            }

            // Get the user's ID from the claims.
            var userIdString = HttpContext.User.Claims.First(c => c.Type.Equals("user_id")).Value;
            int userId       = int.Parse(userIdString);

            var idea = new Idea()
            {
                Id         = await GenerateUniqueId(userId),
                UserId     = userId,
                Content    = request.Content,
                Impact     = (int)request.Impact,
                Ease       = (int)request.Ease,
                Confidence = (int)request.Confidence,
                CreatedAt  = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
            };

            dbContext.Ideas.Add(idea);
            await dbContext.SaveChangesAsync();

            var response = new IdeaResponse(idea.Id, idea.Content, idea.Impact, idea.Ease, idea.Confidence, idea.CreatedAt);

            return(CreatedAtAction(nameof(GetIdeas), response));
        }
Пример #3
0
        public async Task <User> Handle(SignUpUserCommand command, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrWhiteSpace(command.Password))
            {
                throw new AppException("Password is required");
            }

            if (_dataContext.User.Any(x => x.Email == command.Email))
            {
                throw new AppException("Username \"" + command.Email + "\" is already taken");
            }

            _userService.CreatePasswordHash(command.Password, out var passwordHash, out var passwordSalt);

            var user = new User
            {
                First = command.First,
                Last  = command.Last,
                Email = command.Email,
                Hash  = passwordHash,
                Salt  = passwordSalt
            };

            _dataContext.User.Add(user);

            await _dataContext.SaveChangesAsync(cancellationToken);

            var loginUserCommand = new LoginUserCommand
            {
                Email    = command.Email,
                Password = command.Password,
            };

            user = await _mediator.Send(loginUserCommand, cancellationToken);

            await _dataContext.SaveChangesAsync(cancellationToken);

            return(user);
        }
        public async Task <Refresh> Handle(RefreshTokenCommand request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var principal = _tokenService.GetPrincipalFromExpiredToken(request.Token);
            var username  = principal.Identity.Name;

            var user = await _dataContext.User.SingleOrDefaultAsync(x => x.Email == username, cancellationToken);

            if (user.RefreshToken != request.RefreshToken)
            {
                throw new SecurityTokenException("Invalid refresh token");
            }

            var newJwtToken     = _tokenService.GenerateToken(principal.Claims);
            var newRefreshToken = _tokenService.GenerateRefreshToken();

            user.RefreshToken = newRefreshToken;
            await _dataContext.SaveChangesAsync(cancellationToken);

            return(new Refresh
            {
                Token = newJwtToken,
                RefreshToken = newRefreshToken
            });
        }