Ejemplo n.º 1
0
        public async Task <CommonDto> CreateClient(CreateClientBindingModel clientModel)
        {
            var newClientDomain = (Domain.Entity.Client)_clientFactory.GetModel(clientModel);

            newClientDomain.Id = ObjectId.GenerateNewId().ToString();

            if (clientModel.ApplicationType.ToUpper().Equals("JAVA SCRIPT"))
            {
                if (clientModel.AllowedOrigin.Equals("*"))
                {
                    CustomException.ThrowBadRequestException("Provide AllowedOrigin for cors support");
                }

                var secret = newClientDomain.Secret;
                if (string.IsNullOrEmpty(secret))
                {
                    secret = GenerateClientSecret();
                }

                newClientDomain.Secret = GetHash(secret);
                await Context.GetClientCollection().InsertOneAsync(newClientDomain);

                var newClientDto = (CreatedClientDto)_clientFactory.GetModel <CreatedClientDto>(newClientDomain);
                newClientDto.Secret = secret;
                return(newClientDto);
            }

            newClientDomain.Secret        = null;
            newClientDomain.AllowedOrigin = "*";
            await Context.GetClientCollection().InsertOneAsync(newClientDomain);

            return((CreatedClientDto)_clientFactory.GetModel <CreatedClientDto>(newClientDomain));
        }
Ejemplo n.º 2
0
        public async Task <UserCreateClientModel> UserCreateClient(string userId, UserCreateClientBindingModel model)
        {
            var newClient = new Domain.Entity.Client
            {
                Id                   = ObjectId.GenerateNewId().ToString(),
                Active               = true,
                ApplicationType      = GetApplicationTypeEnum(model.ApplicationType),
                UserId               = userId,
                AllowedOrigin        = "*",
                RefreshTokenLifeTime = 10080
            };
            var result = new UserCreateClientModel
            {
                Id      = newClient.Id,
                Message = "client_id: " + newClient.Id
            };

            if (model.ApplicationType.ToUpper().Equals("JAVA SCRIPT"))
            {
                if (string.IsNullOrEmpty(model.AllowedOrigin) || model.AllowedOrigin.Equals("*"))
                {
                    CustomException.ThrowBadRequestException("Provide AllowedOrigin for cors support");
                }

                var secret = GenerateClientSecret();
                newClient.Secret        = GetHash(secret);
                newClient.AllowedOrigin = model.AllowedOrigin;
                result.Message         += Environment.NewLine + "client_secret: " + secret;
            }

            await Context.GetClientCollection().InsertOneAsync(newClient);

            return(result);
        }
Ejemplo n.º 3
0
        public async Task <ICommonDto> UpdateRole(string id, string name)
        {
            var roleExists = await Context.GetRoleCollection().Find(x => x.Id.Equals(id)).AnyAsync();

            if (!roleExists)
            {
                CustomException.ThrowNotFoundException();
            }

            var roleNameExists = await Context.GetRoleCollection().Find(x => x.Name.Equals(name)).AnyAsync();

            if (roleNameExists)
            {
                CustomException.ThrowBadRequestException("Name is taken.");
            }

            var update = Builders <IdentityRole> .Update.Set(x => x.Name, name);

            var updateResult = await Context.GetRoleCollection().UpdateOneAsync(x => x.Id.Equals(id), update);

            if (!updateResult.IsAcknowledged)
            {
                CustomException.ThrowBadRequestException("Update failed.");
            }

            var updatedRole = await Context.GetRoleCollection().Find(x => x.Id.Equals(id)).SingleAsync();

            return(_roleFactory.GetModel <RoleDto>(updatedRole));
        }
Ejemplo n.º 4
0
        public async Task <IHttpActionResult> PutCategory(int id, CategoryDto category)
        {
            if (id != category.Id)
            {
                CustomException.ThrowBadRequestException($"Id: {id} doesn't match.");
            }

            return(Ok(await CategoryService.Update(category)));
        }
Ejemplo n.º 5
0
        public async Task <IHttpActionResult> PutRole(string id, IdentityRoleDto role)
        {
            if (id != role.Id)
            {
                CustomException.ThrowBadRequestException($"Id: {id} doesn't match.");
            }

            return(Ok(await RoleService.Update(role)));
        }
Ejemplo n.º 6
0
        public async Task <IHttpActionResult> PutState(int id, StatePutDto state)
        {
            if (id != state.Id)
            {
                CustomException.ThrowBadRequestException($"Id: {id} doesn't match.");
            }

            return(Ok(await StateService.Update(state)));
        }
Ejemplo n.º 7
0
        public async Task <IHttpActionResult> PutClientNoSecret(string id, ClientNoSecretDto client)
        {
            if (id != client.Id)
            {
                CustomException.ThrowBadRequestException($"Client id: {id} doesn't match.");
            }

            return(Ok(await ClientService.UpdateNoSecret(client)));
        }
Ejemplo n.º 8
0
        public async Task ClientBelongsToUser(string id, string userId)
        {
            var clientBelongsToUser = await Context.GetClientCollection().Find(x => x.Id.Equals(id) && x.UserId.Equals(userId)).AnyAsync();

            if (!clientBelongsToUser)
            {
                CustomException.ThrowBadRequestException("You are not the owner of this client.");
            }
        }
Ejemplo n.º 9
0
        public async Task <IHttpActionResult> PutEvent(long id, EventPutDto @event)
        {
            if (id != @event.Id)
            {
                CustomException.ThrowBadRequestException($"Id: {id} doesn't match.");
            }

            return(Ok(await EventService.Update(@event)));
        }
Ejemplo n.º 10
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var page     = (int)actionContext.ActionArguments["page"];
            var pageSize = (int)actionContext.ActionArguments["pageSize"];

            if (page < 1 || pageSize < 1)
            {
                var ex = new CustomException();
                ex.ThrowBadRequestException("Value of page and pageSize cannot be less than 1");
            }
        }
Ejemplo n.º 11
0
        public async Task <IHttpActionResult> GetMyClient(string id)
        {
            var userName = User.Identity.Name;

            if (!await ClientService.CheckUserClient(userName, id))
            {
                CustomException.ThrowBadRequestException($"There is no client with id = {id} associated with user: {userName}.");
            }

            return(Ok(await ClientService.GetMyClientAsync(userName, id)));
        }
Ejemplo n.º 12
0
        public async Task Delete(string id)
        {
            await MovieExists(id);

            var deleteResult = await Context.GetMovieCollection().DeleteOneAsync(x => x.Id.Equals(id));

            if (!deleteResult.IsAcknowledged)
            {
                CustomException.ThrowBadRequestException("Deleting movie failed.");
            }
        }
Ejemplo n.º 13
0
        private async Task IsJavaScriptClient(string id)
        {
            var isJsClient = await Context.GetClientCollection()
                             .Find(x => x.Id.Equals(id) && x.ApplicationType == ApplicationType.JavaScript)
                             .AnyAsync();

            if (!isJsClient)
            {
                CustomException.ThrowBadRequestException("This is not Java Script client");
            }
        }
Ejemplo n.º 14
0
        private async Task <ICommonDto> ProcessUpdateArrayElements(string id, UpdateDefinition <Domain.Entity.Movie> updateBuilder)
        {
            var updateResult = await Context.GetMovieCollection().UpdateOneAsync(x => x.Id.Equals(id), updateBuilder);

            if (!updateResult.IsAcknowledged)
            {
                CustomException.ThrowBadRequestException("Update failed.");
            }

            var updatedMovie = await Context.GetMovieCollection().Find(x => x.Id.Equals(id)).SingleAsync();

            return(_movieFactory.GetModel <MovieDto>(updatedMovie));
        }
Ejemplo n.º 15
0
        public async Task DeleteMyAccount(string id)
        {
            await UserExists(id);

            var update = Builders <Domain.Entity.User> .Update.Set(x => x.IsActive, false);

            var updateResult = await Context.GetUserCollection().UpdateOneAsync(x => x.Id.Equals(id), update);

            if (!updateResult.IsAcknowledged)
            {
                CustomException.ThrowBadRequestException("Fail.");
            }
        }
Ejemplo n.º 16
0
        public override async Task <IdentityRoleDto> AddAsync(IdentityRolePostModel dtoModel)
        {
            if (await RoleExistsAsync(dtoModel.RoleName))
            {
                CustomException.ThrowBadRequestException($"Role: {dtoModel.RoleName} already exists.");
            }

            var role = _roleModelFactory.GetModel(dtoModel);
            await _roleManager.CreateAsync(role);

            var newRole = await _roleManager.FindByNameAsync(dtoModel.RoleName);

            return(_roleModelFactory.GetModel(newRole));
        }
Ejemplo n.º 17
0
        public async Task <ICommonDto> UpdateMovie(string id, UpdateMovieBindingModel model)
        {
            await MovieExists(id);

            var updateResult = await UpdateMovieAction(id, model);

            if (!updateResult.IsAcknowledged)
            {
                CustomException.ThrowBadRequestException("Client update failed.");
            }

            var updatedMovie = await Context.GetMovieCollection().Find(x => x.Id.Equals(id)).SingleAsync();

            return(_movieFactory.GetModel <MovieDto>(updatedMovie));
        }
Ejemplo n.º 18
0
        public async Task <ICommonDto> UpdateMyAccount(string id, UpdateMyAccountBindingModel model)
        {
            await UserExists(id);

            var updateResult = await UpdateUser(id, model);

            if (!updateResult.IsAcknowledged)
            {
                CustomException.ThrowBadRequestException("Change origin failed.");
            }

            var user = await Context.GetUserCollection().Find(x => x.Id.Equals(id)).SingleAsync();

            return(_userFactory.GetModel <MyAccountDto>(user));
        }
Ejemplo n.º 19
0
        public async Task <IHttpActionResult> PutMyClient(string id, ClientNoSecretDto client)
        {
            var userName = User.Identity.Name;

            if (!await ClientService.CheckUserClient(userName, id))
            {
                CustomException.ThrowBadRequestException($"There is no client with id = {id} associated with user: {userName}.");
            }

            if (id != client.Id)
            {
                CustomException.ThrowBadRequestException($"Client id: {id} doesn't match.");
            }

            return(Ok(await ClientService.UpdateNoSecret(client)));
        }
Ejemplo n.º 20
0
        public async Task DeleteRole(string id)
        {
            var roleExists = await Context.GetRoleCollection().Find(x => x.Id.Equals(id)).AnyAsync();

            if (!roleExists)
            {
                CustomException.ThrowNotFoundException();
            }

            var deleteResult = await Context.GetRoleCollection().DeleteOneAsync(x => x.Id.Equals(id));

            if (!deleteResult.IsAcknowledged)
            {
                CustomException.ThrowBadRequestException("Delete failed.");
            }
        }
Ejemplo n.º 21
0
        public async Task <IHttpActionResult> PostClient(ClientPostDto client)
        {
            var user = await UserManager.FindByEmailAsync(client.Username);

            if (user == null)
            {
                CustomException.ThrowNotFoundException($"User: {client.Username} doesn't exist.");
            }

            var       messageToSend = "Username: "******"Please provide origin for JavaScript web application.");
                }

                if (client.AllowedOrigin.Equals("*"))
                {
                    CustomException.ThrowBadRequestException("Sorry we cannot allow unlimited origin. Please provide direct domain address.");
                }

                newClient = await ClientService.AddAsync(client);

                messageToSend += "<br>" + "client_id: " + newClient.Id;
            }
            else
            {
                var clientSecret = ClientService.GenerateClientSecret();

                client.ClientSecret  = clientSecret;
                client.AllowedOrigin = "*";

                newClient = await ClientService.AddAsync(client);

                messageToSend         += "<br>" + "client_id: " + newClient.Id + "<br>" + "client_secret: " + clientSecret;
                newClient.ClientSecret = clientSecret;
            }


            await UserManager.SendEmailAsync(user?.Id, "New client", $"{messageToSend}");

            return(CreatedAtRoute("ClientRoute", new { id = newClient.Id }, newClient));
        }
Ejemplo n.º 22
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ActionArguments.ContainsKey("id"))
            {
                var id = (string)actionContext.ActionArguments["id"];

                try
                {
                    var result = ObjectId.Parse(id);
                }
                catch (FormatException e)
                {
                    var ex = new CustomException();
                    ex.ThrowBadRequestException(e.Message);
                }
            }
        }
Ejemplo n.º 23
0
        public async Task <ICommonDto> ChangeOrigin(string id, string userId, string origin)
        {
            await ClientExists(id);
            await ClientBelongsToUser(id, userId);
            await IsJavaScriptClient(id);

            var update = Builders <Domain.Entity.Client> .Update.Set(x => x.AllowedOrigin, origin);

            var updateResult = await Context.GetClientCollection().UpdateOneAsync(x => x.Id.Equals(id), update);

            if (!updateResult.IsAcknowledged)
            {
                CustomException.ThrowBadRequestException("Change origin failed.");
            }

            return(await GetUserCreatedClient(id));
        }
Ejemplo n.º 24
0
        public async Task <ICommonDto> CreateRole(string name)
        {
            var roleExists = await Context.GetRoleCollection().Find(x => x.Name.Equals(name)).AnyAsync();

            if (roleExists)
            {
                CustomException.ThrowBadRequestException("Role already exists.");
            }

            var newRole = new IdentityRole
            {
                Name = name
            };

            await Context.GetRoleCollection().InsertOneAsync(newRole);

            return(_roleFactory.GetModel <CreatedRole>(newRole));
        }
Ejemplo n.º 25
0
        public async Task <IHttpActionResult> RemoveUserRole(UserRoleModel model)
        {
            var user = await UserManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                CustomException.ThrowNotFoundException($"There is no user {model.Email}.");
            }

            if (!await UserManager.IsInRoleAsync(user?.Id, model.RoleName))
            {
                CustomException.ThrowBadRequestException($"User {model.Email} is not in role {model.RoleName}.");
            }

            IdentityResult result = await UserManager.RemoveFromRoleAsync(user?.Id, model.RoleName);

            return(result.Succeeded ? Ok() : GetErrorResult(result));
        }
Ejemplo n.º 26
0
        public async Task <string> GenerateNewClientSecret(string id, string userId)
        {
            await ClientExists(id);
            await ClientBelongsToUser(id, userId);
            await IsJavaScriptClient(id);

            var newSecret = GenerateClientSecret();
            var update    = Builders <Domain.Entity.Client> .Update.Set(x => x.Secret, GetHash(newSecret));

            var result = await Context.GetClientCollection().UpdateOneAsync(x => x.Id.Equals(id), update);

            if (!result.IsAcknowledged)
            {
                CustomException.ThrowBadRequestException("Generating new client_id failed.");
            }

            return("client_id: " + id + Environment.NewLine + "client_secret: " + newSecret);
        }
Ejemplo n.º 27
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ActionArguments.ContainsKey("paginationModel"))
            {
                var model = (Pagination)actionContext.ActionArguments["paginationModel"];

                long numericPage;
                long numericPageSize;
                var  isPageNumeric     = long.TryParse(model.Page, out numericPage);
                var  isPageSizeNumeric = long.TryParse(model.PageSize, out numericPageSize);


                if (!(isPageNumeric && isPageSizeNumeric))
                {
                    var ex = new CustomException();
                    ex.ThrowBadRequestException("Value of page and pageSize has to be numeric string.");
                }
            }
        }
Ejemplo n.º 28
0
        public async Task <IHttpActionResult> ResetMyClientSecret([FromBody] ResetClientSecretBindingModel model)
        {
            var userName = User.Identity.Name;

            if (!await ClientService.CheckUserClient(userName, model.Id))
            {
                CustomException.ThrowBadRequestException($"There is no client with id = {model.Id} associated with user: {userName}.");
            }

            var user = await UserManager.FindByEmailAsync(userName);

            var client = await ClientService.GetMyClientAsync(userName, model.Id);

            if (!client.Active)
            {
                CustomException.ThrowBadRequestException($"Client with id = {client.Id} is no more valid.");
            }

            var newClientSecret = ClientService.GenerateClientSecret();

            var clientToUpdate = new ClientDto
            {
                Id                   = model.Id,
                ClientSecret         = newClientSecret,
                Username             = userName,
                Active               = client.Active,
                RefreshTokenLifeTime = client.RefreshTokenLifeTime,
                ApplicationType      = ApplicationTypes.NativeConfidential,
                AllowedOrigin        = client.AllowedOrigin
            };

            var updatedClient = await ClientService.Update(clientToUpdate);

            var messageToSend = "Username: "******"<br>" + "client_id: " + client.Id +
                                "<br>" + "client_secret: " + newClientSecret;

            await UserManager.SendEmailAsync(user.Id, "Client secret changed", $"{messageToSend}");

            return(Ok(updatedClient));
        }
Ejemplo n.º 29
0
        public async Task <UserRolesDto> AddRolesToUser(string id, List <string> roles)
        {
            await UserExists(id);

            var user = await Context.GetUserCollection().Find(x => x.Id.Equals(id)).SingleAsync();

            var allRoleNames = await _roleService.GetAllNames();

            var rolesNotExists = roles.Except(allRoleNames).ToList();

            if (rolesNotExists.Any())
            {
                CustomException.ThrowBadRequestException($"Roles '{string.Join(",", rolesNotExists)}' does not exixts.");
            }

            var rolesToAdd = roles.Except(user.Roles).ToList();

            user.Roles.AddRange(rolesToAdd);

            var update = Builders <Domain.Entity.User> .Update.Set(x => x.Roles, user.Roles);

            var result = await Context.GetUserCollection().UpdateOneAsync(x => x.Id.Equals(id), update);

            if (!result.IsAcknowledged)
            {
                CustomException.ThrowBadRequestException("Adding roles failed.");
            }

            var roleList = new List <IdentityRole>();

            foreach (var userRole in user.Roles)
            {
                var role = await _roleService.GetByName(userRole);

                roleList.Add(role);
            }

            return(_userFactory.GetModel(id, roleList));
        }
Ejemplo n.º 30
0
        public async Task <ICommonDto> UpdateClient(string id, UpdateClientBindingModel clientModel)
        {
            await ClientExists(id);

            if (!string.IsNullOrEmpty(clientModel.ApplicationType) && clientModel.ApplicationType.ToUpper().Equals("JAVA SCRIPT"))
            {
                if (string.IsNullOrEmpty(clientModel.AllowedOrigin) || clientModel.AllowedOrigin.Equals("*"))
                {
                    CustomException.ThrowBadRequestException("Provide AllowedOrigin for cors support");
                }

                if (string.IsNullOrEmpty(clientModel.Secret))
                {
                    clientModel.Secret = GenerateClientSecret();
                }
            }
            else
            {
                clientModel.AllowedOrigin = "*";
                clientModel.Secret        = null;
            }

            var updateResult = await UpdateClientAction(id, clientModel);

            if (!updateResult.IsAcknowledged)
            {
                CustomException.ThrowBadRequestException("Client update failed.");
            }

            var updatedClient = await Context.GetClientCollection().Find(x => x.Id.Equals(id)).SingleAsync();

            var updatedClientDto = (UpdatedClientDto)_clientFactory.GetModel <UpdatedClientDto>(updatedClient);

            updatedClientDto.Secret = clientModel.Secret;
            return(updatedClientDto);
        }