public async Task <IActionResult> RegisterUser([FromBody] Client.Models.Users.UserRegistrationInfo registrationInfo, CancellationToken cancellationToken)
        {
            if (registrationInfo == null)
            {
                var error = ServiceErrorResponses.BodyIsMissing("RegistrationInfo");
                return(BadRequest(error));
            }

            if (registrationInfo.Login == null || registrationInfo.Password == null)
            {
                var error = ServiceErrorResponses.NotEnoughUserData();
                return(BadRequest(error));
            }

            var creationInfo = new UserCreationInfo(registrationInfo.Login, Auth.AuthHash.GetHashPassword(registrationInfo.Password));

            User user = null;

            try
            {
                user = await users.CreateAsync(creationInfo, cancellationToken);
            }
            catch (UserDuplicationException)
            {
                var error = ServiceErrorResponses.UserNameAlreadyExists(registrationInfo.Login);
                return(BadRequest(error));
            }

            var clientUser = UserConverter.Convert(user);

            return(Ok(clientUser));
        }
Пример #2
0
        public async Task <IActionResult> RegisterUser([FromBody] Client.Models.Users.UserRegistrationInfo registrationInfo, [FromServices] IJwtSigningEncodingKey signingEncodingKey, CancellationToken cancellationToken)
        {
            if (registrationInfo == null)
            {
                var error = ServiceErrorResponses.BodyIsMissing("RegistrationInfo");
                return(BadRequest(error));
            }

            if (registrationInfo.Login == null || registrationInfo.Password == null)
            {
                var error = ServiceErrorResponses.NotEnoughUserData();
                return(BadRequest(error));
            }

            var creationInfo = new UserCreationInfo(registrationInfo.Login, Auth.AuthHash.GetHashPassword(registrationInfo.Password));

            User user = null;

            try
            {
                user = await users.CreateAsync(creationInfo, cancellationToken);
            }
            catch (UserDuplicationException)
            {
                var error = ServiceErrorResponses.UserNameAlreadyExists(registrationInfo.Login);
                return(BadRequest(error));
            }

            var clientUser = UserConverter.Convert(user);

            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, clientUser.Login),

                new Claim(ClaimTypes.NameIdentifier, clientUser.Id),
            };

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(JWT.GetJWT(claims, signingEncodingKey));

            return(Ok(new AuthTokenAnswer
            {
                AccessToken = encodedJwt
            }));
        }