Exemplo n.º 1
0
        public async Task <User> CreateAsync(UserCreationInfo creationInfo, CancellationToken cancellationToken)
        {
            if (creationInfo == null)
            {
                throw new ArgumentNullException(nameof(creationInfo));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var findResultsDuplicate = await users.FindAsync(u => u.Login == creationInfo.Login, cancellationToken : cancellationToken);

            var userDuplicate = await findResultsDuplicate.FirstOrDefaultAsync(cancellationToken);

            if (userDuplicate != null)
            {
                throw new UserDuplicationException(creationInfo.Login);
            }

            var user = new User
            {
                Id           = Guid.NewGuid(),
                Login        = creationInfo.Login,
                PasswordHash = creationInfo.PasswodHash,
                RegisteredAt = DateTime.UtcNow
            };

            InsertOneOptions options = null;
            await users.InsertOneAsync(user, options, cancellationToken);

            return(await Task.FromResult(user));
        }
        public Task <User> CreateAsync(UserCreationInfo creationInfo, CancellationToken cancellationToken)
        {
            if (creationInfo == null)
            {
                throw new ArgumentNullException(nameof(creationInfo));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var userDuplicate = _users.Find <User>(u => u.Login == creationInfo.Login).FirstOrDefault();

            if (userDuplicate != null)
            {
                throw new UserDuplicationException(creationInfo.Login);
            }

            var user = new User
            {
                Id           = Guid.NewGuid(),
                Login        = creationInfo.Login,
                PasswordHash = creationInfo.PasswodHash,
                RegisteredAt = DateTime.UtcNow
            };

            _users.InsertOne(user);
            return(Task.FromResult(user));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Создать нового пользователя
        /// </summary>
        /// <param name="creationInfo">Данные для создания нового пользователя</param>
        /// <param name="cancellationToken">Токен отмены операции</param>
        /// <returns>Созданный пользователь</returns>
        public Task <User> CreateAsync(UserCreationInfo creationInfo, CancellationToken cancellationToken)
        {
            if (creationInfo == null)
            {
                throw new ArgumentNullException(nameof(creationInfo));
            }

            cancellationToken.ThrowIfCancellationRequested();

            if (this.loginIndex.ContainsKey(creationInfo.Login))
            {
                throw new UserDuplicationException(creationInfo.Login);
            }

            var id  = Guid.NewGuid();
            var now = DateTime.UtcNow;

            var user = new User
            {
                Id           = id,
                Login        = creationInfo.Login,
                PasswordHash = creationInfo.PasswodHash,
                RegisteredAt = now
            };

            this.primaryKeyIndex.Add(id, user);
            this.loginIndex.Add(user.Login, user);

            return(Task.FromResult(user));
        }
        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));
        }
Exemplo n.º 5
0
        public async Task <IActionResult> Register([FromBody] Client.Users.UserRegistrationInfo registrationInfo,
                                                   CancellationToken cancellationToken)
        {
            if (registrationInfo == null)
            {
                var error = ServiceErrorResponses.BodyIsMissing("UserRegistrationInfo");
                return(this.BadRequest(error));
            }

            User result;
            var  creationInfo = new UserCreationInfo(registrationInfo.Login,
                                                     Authenticator.HashPassword(registrationInfo.Password), registrationInfo.FirstName,
                                                     registrationInfo.LastName, registrationInfo.Email, registrationInfo.Phone);

            try
            {
                result = await userRepository.CreateAsync(creationInfo, cancellationToken);
            }
            catch (UserDuplicationException)
            {
                var error = ServiceErrorResponses.ConflictLogin(creationInfo?.Login);
                return(this.Conflict(error));
            }

            var clientUser = UserConverter.Convert(result);

            return(this.Ok(clientUser));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> CreateUserAsync([FromBody] Client.UserCreationInfo creationInfo,
                                                          CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (creationInfo == null)
            {
                var error = ServiceErrorResponses.BodyIsMissing("UserCreationInfo");
                return(BadRequest(error));
            }

            var  hashPassword      = PasswordEncoder.Encode(creationInfo.Password);
            var  modelCreationInfo = new UserCreationInfo(creationInfo.Login, hashPassword);
            User modelUser         = null;

            try
            {
                modelUser = await repository.CreateAsync(modelCreationInfo, cancellationToken)
                            .ConfigureAwait(false);
            }
            catch (UserDuplicationException)
            {
                var error = ServiceErrorResponses.UserDuplication(modelCreationInfo.Login);
                return(BadRequest(error));
            }

            var clientUser = UserConverter.Convert(modelUser);

            return(Ok(clientUser));
        }
Exemplo n.º 7
0
        public Task <User> CreateAsync(UserCreationInfo creationInfo, CancellationToken cancellationToken)
        {
            if (creationInfo == null)
            {
                throw new ArgumentNullException(nameof(creationInfo));
            }

            cancellationToken.ThrowIfCancellationRequested();

            if (this.users.Find(x => x.Login == creationInfo.Login).Any())
            {
                throw new UserDuplicationException(creationInfo.Login);
            }

            var id  = Guid.NewGuid();
            var now = DateTime.UtcNow;

            var user = new User
            {
                Id           = id,
                Login        = creationInfo.Login,
                PasswordHash = creationInfo.PasswodHash,
                RegisteredAt = now
            };

            users.InsertOne(user);

            return(Task.FromResult(user));
        }
Exemplo n.º 8
0
        public RegisterResult Register(string login, string password)
        {
            if (login == null)
            {
                throw new ArgumentNullException(nameof(login));
            }

            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }
            var hash         = Models.Helper.Hash(password);
            var creationInfo = new UserCreationInfo(login, hash);
            CancellationToken cancellationToken;
            User user = null;

            try
            {
                user = this.userRepository.CreateAsync(creationInfo, cancellationToken).Result;
            }
            catch (UserDuplicationException)
            {
                throw new RegistrationException();
            }
            return(new RegisterResult(user.Login, user.RegisteredAt));
        }
        /// <summary>
        /// Creates a user on your Echosign account.
        /// </summary>
        /// <param name="info">The info of the user you want to create.</param>
        /// <returns></returns>
        public async Task <UserCreationResponse> CreateUser(UserCreationInfo info)
        {
            string serializedObject = JsonConvert.SerializeObject(info);

            using (StringContent content = new StringContent(serializedObject, Encoding.UTF8))
            {
                content.Headers.Remove("Content-Type");
                content.Headers.Add("Content-Type", "application/json");

                HttpResponseMessage result = await client.PostAsync(apiEndpointVer + "/users", content).ConfigureAwait(false);

                if (result.IsSuccessStatusCode)
                {
                    string response = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

                    UserCreationResponse user = JsonConvert.DeserializeObject <UserCreationResponse>(response);

                    return(user);
                }
                else
                {
                    string response = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

                    HandleError(result.StatusCode, response, false);

                    return(null);
                }
            }
        }
Exemplo n.º 10
0
        public Task <User> CreateAsync(UserCreationInfo creationInfo, CancellationToken cancellationToken)
        {
            if (creationInfo == null)
            {
                throw new ArgumentNullException(nameof(creationInfo));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var countUsersWithSameLogin = users.Find(usr => usr.Login == creationInfo.Login).CountDocuments();

            if (countUsersWithSameLogin > 0)
            {
                throw new UserDuplicationException(creationInfo.Login);
            }

            var user = new User
            {
                Login         = creationInfo.Login,
                PasswordHash  = creationInfo.PasswodHash,
                RegisteredAt  = DateTime.Now,
                FirstName     = creationInfo.FirstName,
                LastName      = creationInfo.LastName,
                Email         = creationInfo.Email,
                Phone         = creationInfo.Phone,
                LastUpdatedAt = DateTime.Now
            };

            users.InsertOne(user);

            return(Task.FromResult(user));
        }
Exemplo n.º 11
0
        public async Task Token1([FromBody] UserRegistrationInfo registrationInfo, CancellationToken cancellationToken)
        {
            var username = registrationInfo.Login;
            var password = registrationInfo.Password;

            var creationInfo = new UserCreationInfo(username, this.HashPassword(password));
            var getUser      = this.userRepository.Get(username);

            if (getUser != null)
            {
                Response.StatusCode = 400;
                await Response.WriteAsync("user already exists");

                throw new UserDuplicationException(registrationInfo.Login);
            }

            try
            {
                this.userRepository.Create(creationInfo);
            }
            catch (UserNotFoundException)
            {
                throw new AuthenticationException();
            }

            var identity = this.GetIdentity(username, password);

            if (identity == null)
            {
                this.Response.StatusCode = 400;
                await this.Response.WriteAsync("Invalid username or password.");

                return;
            }

            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
            };

            // сериализация ответа
            this.Response.ContentType = "application/json";
            await this.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }
Exemplo n.º 12
0
        public async Task <IUser> CreateAsync(UserCreationInfo createUserArgs)
        {
            var user = this.mapper.Map <User>(createUserArgs);

            user.UserId            = this.guidFactory.CreateNew().ToString();
            user.State             = UserState.Active;
            user.EncreptedPassword = this.hashComputer.Compute(createUserArgs.Password);
            await this.AddAsync(user);

            return(await Task.FromResult(user));
        }
Exemplo n.º 13
0
        /// <summary>
        ///     Creates a new user in the Adobe Sign system
        /// </summary>
        /// <param name="accessToken">
        ///     An &lt;a href&#x3D;\&quot;#\&quot; onclick&#x3D;\&quot;this.href&#x3D;oauthDoc()\&quot;
        ///     oncontextmenu&#x3D;\&quot;this.href&#x3D;oauthDoc()\&quot; target&#x3D;\&quot;oauthDoc\&quot;&gt;OAuth Access Token
        ///     &lt;/a&gt; with scopes:&lt;ul&gt;&lt;li style&#x3D;&#39;list-style-type: square&#39;&gt;&lt;a href&#x3D;\&quot;#\
        ///     &quot; onclick&#x3D;\&quot;this.href&#x3D;oauthDoc(&#39;user_write&#39;)\&quot; oncontextmenu&#x3D;\&quot;this.href
        ///     &#x3D;oauthDoc(&#39;user_write&#39;)\&quot; target&#x3D;\&quot;oauthDoc\&quot;&gt;user_write&lt;/a&gt;&lt;/li&gt;
        ///     &lt;/ul&gt;
        /// </param>
        /// <param name="userCreationInfo"></param>
        /// <param name="xApiUser">
        ///     The userId or email of API caller using the account or group token in the format &lt;b&gt;
        ///     userid:{userId} OR email:{email}.&lt;/b&gt; If it is not specified, then the caller is inferred from the token.
        /// </param>
        /// <returns>UserCreationResponse</returns>
        public UserCreationResponse CreateUser(string accessToken, UserCreationInfo userCreationInfo, string xApiUser)
        {
            // verify the required parameter 'accessToken' is set
            if (accessToken == null)
            {
                throw new ApiException(400, "Missing required parameter 'accessToken' when calling CreateUser");
            }

            // verify the required parameter 'userCreationInfo' is set
            if (userCreationInfo == null)
            {
                throw new ApiException(400, "Missing required parameter 'userCreationInfo' when calling CreateUser");
            }


            string path = "/users";

            path = path.Replace("{format}", "json");

            Dictionary <string, string>        queryParams  = new Dictionary <string, string>();
            Dictionary <string, string>        headerParams = new Dictionary <string, string>();
            Dictionary <string, string>        formParams   = new Dictionary <string, string>();
            Dictionary <string, FileParameter> fileParams   = new Dictionary <string, FileParameter>();
            string postBody = null;

            if (accessToken != null)
            {
                headerParams.Add("Access-Token", ApiClient.ParameterToString(accessToken));                      // header parameter
            }
            if (xApiUser != null)
            {
                headerParams.Add("x-api-user", ApiClient.ParameterToString(xApiUser)); // header parameter
            }
            postBody = ApiClient.Serialize(userCreationInfo);                          // http body (model) parameter

            // authentication setting, if any
            string[] authSettings = { };

            // make the HTTP request
            IRestResponse response = (IRestResponse)ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);

            if ((int)response.StatusCode >= 400)
            {
                throw new ApiException((int)response.StatusCode, "Error calling CreateUser: "******"Error calling CreateUser: " + response.ErrorMessage, response.ErrorMessage);
            }

            return((UserCreationResponse)ApiClient.Deserialize(response.Content, typeof(UserCreationResponse), response.Headers));
        }
Exemplo n.º 14
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
            }));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Создать нового пользователя
        /// </summary>
        /// <param name="creationInfo">Данные для создания нового пользователя</param>
        /// <param name="cancellationToken">Токен отмены операции</param>
        /// <returns>Созданный пользователь</returns>
        public User1 CreateAsync(UserCreationInfo creationInfo)
        {
            if (creationInfo == null)
            {
                throw new ArgumentNullException(nameof(creationInfo));
            }

            //cancellationToken.ThrowIfCancellationRequested();

            //if (this.loginIndex.ContainsKey(creationInfo.Login))
            //{
            //    throw new UserDuplicationException(creationInfo.Login);
            //}

            var id  = Guid.NewGuid();
            var now = DateTime.UtcNow;

            var user = new User1
            {
                Id           = id,
                Login        = creationInfo.Login,
                PasswordHash = creationInfo.PasswodHash,
                RegisteredAt = now
            };

            string CurrentDir = @"D:\univer\6 sem\tok\TokenApp\TokenApp\todoList.db";

            using (SQLiteConnection connection = new SQLiteConnection(string.Format("Data Source={0};", CurrentDir)))
            {
                connection.Open();
                using (var command2 = new SQLiteCommand("INSERT INTO 'users' ('userid', 'login', 'password', 'registeredat') VALUES ('" + user.Id.ToString() + "', '" + user.Login + "', '"
                                                        + user.PasswordHash + "', '" + user.RegisteredAt.ToString() + "');", connection))
                {
                    var a = command2.ExecuteNonQuery();
                    connection.Close();
                }
            }

            //this.primaryKeyIndex.Add(id, user);
            //this.loginIndex.Add(user.Login, user);

            return(user);
        }
Exemplo n.º 16
0
        public async Task <User> CreateAsync(UserCreationInfo creationInfo, CancellationToken cancellationToken)
        {
            var userDuplicate = await this.GetAsync(creationInfo.Login, cancellationToken);

            if (userDuplicate != null)
            {
                throw new UserDuplicationException(creationInfo.Login);
            }

            User user = new User()
            {
                Id           = Guid.NewGuid(),
                Login        = creationInfo.Login,
                PasswordHash = creationInfo.PasswodHash,
                RegisteredAt = DateTime.UtcNow
            };

            await users.InsertOneAsync(user, cancellationToken);

            return(await Task.FromResult(user));
        }
Exemplo n.º 17
0
        Register([FromBody] UserRegistrationInfo registrationInfo, CancellationToken cancellationToken)
        {
            if (registrationInfo == null)
            {
                var error = ServiceErrorResponses.BodyIsMissing("TodoRegistrationInfo");
                return(BadRequest(error));
            }

            var info = new UserCreationInfo(registrationInfo.Login,
                                            Authenticator.HashPassword(registrationInfo.Password));

            try
            {
                await _userRepository.CreateAsync(info, cancellationToken);
            }
            catch (UserDuplicationException exception)
            {
                return(BadRequest(exception));
            }

            return(Ok());
        }
Exemplo n.º 18
0
        public Task<User> CreateAsync(UserCreationInfo creationInfo, CancellationToken cancellationToken)
        {
            if (creationInfo == null)
            {
                throw new ArgumentException(nameof(creationInfo));
            }

            cancellationToken.ThrowIfCancellationRequested();
            
            var userWithSameLogin = users.Find(item => item.Login == creationInfo.Login).FirstOrDefault();

            if (userWithSameLogin != null)
            {
                throw new UserDuplicationException(userWithSameLogin.Login);
            }
            
            var id = Guid.NewGuid();
            var now = DateTime.Now;
            var user = new User(id, creationInfo.Login, creationInfo.PasswodHash, now);

            users.InsertOne(user);

            return Task.FromResult(user);
        }
Exemplo n.º 19
0
        public async Task <UserClaim> ExecuteAsync(UserCreationInfo userCreationInfo)
        {
            var user = await this.userRepository.CreateAsync(userCreationInfo);

            return(this.mapper.Map <UserClaim>(user));
        }