Beispiel #1
0
        private async Task <gUser> UpdatePassword(gUser SelectedUser)
        {
            /// find the current user details from the database
            gUser userDetails = await DbContext.Users.FindAsync(SelectedUser.Id).ConfigureAwait(false);

            if (userDetails == null)
            {
                gAppConst.Error(ref ErrorsList, "User not found!");
                return(null);
            }

            /// generate new password reset token
            string passResetToken = await UserManager.GeneratePasswordResetTokenAsync(userDetails).ConfigureAwait(false);

            /// reset user's password
            IdentityResult result = await UserManager.ResetPasswordAsync(
                userDetails, passResetToken, SelectedUser.NewPassword).ConfigureAwait(false);

            /// if result is Failed
            if (!result.Succeeded)
            {
                foreach (var item in result.Errors)
                {
                    ErrorsList.Add(new gError(item.Code, item.Description));
                }
                return(null);
            }

            /// else the result is a success.
            return(userDetails);
        }
Beispiel #2
0
        public async Task <IActionResult> PutMyPassword([FromBody] gUser modifiedUser)
        {
            try
            {
                int.TryParse(User.Claims.First(c => c.Type == "UserId").Value, out int userId);
                if (modifiedUser.Id != userId)
                {
                    gAppConst.Error(ref ErrorsList, "Not Authorised!");
                    return(BadRequest(ErrorsList));
                }

                gUser result = await UpdatePassword(modifiedUser).ConfigureAwait(false);

                if (result != null)
                {
                    return(Ok(result));
                }

                return(BadRequest(ErrorsList));
            }
            catch (Exception) // DbUpdateException, DbUpdateConcurrencyException
            {
                /// Add the error below to the error list and return bad request
                gAppConst.Error(ref ErrorsList, $"Server Issue. Please Contact Administrator.");
                return(BadRequest(ErrorsList));
            }
        }
Beispiel #3
0
        [Authorize(gAppConst.AccessPolicies.LevelOne)]  /// Done
        public async Task <IActionResult> Delete([FromBody] gUser thisUser)
        {
            try
            {
                /// if the User record with the same id is not found
                if (!await DbContext.Users.AnyAsync(u => u.Id == thisUser.Id).ConfigureAwait(false))
                {
                    gAppConst.Error(ref ErrorsList, "User not found");
                    return(BadRequest(ErrorsList));
                }

                /// else the User is found
                /// now delete the user record
                DbContext.Users.Remove(await DbContext.Users.FindAsync(thisUser.Id).ConfigureAwait(false));

                /// save the changes to the database
                await DbContext.SaveChangesAsync().ConfigureAwait(false);

                /// return 200 Ok status
                return(Ok($"User ID ('{thisUser.Id}') was deleted"));
            }
            catch (Exception)
            {
                /// Add the error below to the error list and return bad Department
                gAppConst.Error(ref ErrorsList, $"Server Issue. Please Contact Administrator.");
                return(BadRequest(ErrorsList));
            }
        }
Beispiel #4
0
        [Authorize(gAppConst.AccessPolicies.LevelOne)]  /// Done
        public async Task <IActionResult> Put([FromBody] gUser modifiedUser)
        {
            try
            {
                /// Try to validate the model
                TryValidateModel(modifiedUser);
                /// remove the passwordHash and confrimPassword since
                /// the password update gets handled by another method in this class
                ModelState.Remove("PasswordHash");
                if (!ModelState.IsValid)
                {
                    /// extract the errors and return bad request containing the errors
                    gAppConst.ExtractErrors(ModelState, ref ErrorsList);
                    return(BadRequest(ErrorsList));
                }

                /// if the user record with the same id is not found
                if (!await DbContext.Users.AnyAsync(u => u.Id == modifiedUser.Id).ConfigureAwait(false))
                {
                    gAppConst.Error(ref ErrorsList, "User not found");
                    return(BadRequest(ErrorsList));
                }
                modifiedUser.Department = await DbContext.Departments.FindAsync(modifiedUser.Department.Id).ConfigureAwait(false);

                modifiedUser.Role = await DbContext.Roles.FindAsync(modifiedUser.Role.Id).ConfigureAwait(false);

                /// find the current user details from the database
                gUser userDetails = await DbContext.Users.FindAsync(modifiedUser.Id).ConfigureAwait(false);

                /// update the user details with the new details
                userDetails.FirstName   = modifiedUser.FirstName;
                userDetails.Surname     = modifiedUser.Surname;
                userDetails.Email       = modifiedUser.Email;
                userDetails.PhoneNumber = modifiedUser.PhoneNumber;
                userDetails.Role        = modifiedUser.Role;
                userDetails.Department  = modifiedUser.Department;

                /// thus update user in the context
                DbContext.Users.Update(userDetails);

                /// save the changes to the database
                await DbContext.SaveChangesAsync().ConfigureAwait(false);

                /// thus return 200 ok status with the updated object
                return(Ok(userDetails));
            }
            catch (Exception) // DbUpdateException, DbUpdateConcurrencyException
            {
                /// Add the error below to the error list and return bad request
                gAppConst.Error(ref ErrorsList, $"Server Issue. Please Contact Administrator.");
                return(BadRequest(ErrorsList));
            }
        }
Beispiel #5
0
        /// <summary>
        ///  Update db
        /// </summary>
        private async Task <string> RequestUpdateDb(FileCompleteContext ctx, gUser user)
        {
            var avatarUrl = ctx.HttpContext.Request.Scheme + "://" + ctx.HttpContext.Request.Host.Value + "/api/file/avatar/" + user.Id;
            var response  = await _fileMngClient.SaveAvatarAsync(new gSaveAvatarRequest()
            {
                AvatarUrl = avatarUrl
            });

            if (response == null)
            {
                _logger.LogError("Unknown error occured while requesting user info");
            }
            if (response.Status.Status != Protos.RequestStatus.Success)
            {
                _logger.LogError(response.Status.Message);
            }
            return(avatarUrl);
        }
Beispiel #6
0
        /// <summary>
        /// Handle the upload completion
        /// </summary>
        protected override async Task OnUploadCompleted(FileCompleteContext ctx)
        {
            try
            {
                gUser user = await MoveFilesToFolder(ctx);

                // Update db
                string avatarUrl = await RequestUpdateDb(ctx, user);

                // Attach avatar info to header, because tus send 204 (no response body is allowed)
                ctx.HttpContext.Response.Headers.Add("upload-data", Helpers.JsonSerialize(new { AvatarUrl = avatarUrl }));
            }
            catch (Exception _ex)
            {
                _logger.LogError(_ex.Message);
                throw _ex;
            }
        }
Beispiel #7
0
        public async Task <IActionResult> PutPassword([FromBody] gUser modifiedUser)
        {
            try
            {
                gUser result = await UpdatePassword(modifiedUser).ConfigureAwait(false);

                if (result != null)
                {
                    return(Ok(result));
                }

                return(BadRequest(ErrorsList));
            }
            catch (Exception) // DbUpdateException, DbUpdateConcurrencyException
            {
                /// Add the error below to the error list and return bad request
                gAppConst.Error(ref ErrorsList, $"Server Issue. Please Contact Administrator.");
                return(BadRequest(ErrorsList));
            }
        }
Beispiel #8
0
        [HttpPut("put/{userId}/{isBlocked}")]  /// Done
        public async Task <IActionResult> Put(int userId, bool isBlocked)
        {
            try
            {
                /// if the user with the same id is not found
                gUser user = await DbContext.Users.Include(u => u.Role).Include(u => u.Department).FirstAsync(u => u.Id == userId).ConfigureAwait(false);

                if (user == null)
                {
                    gAppConst.Error(ref ErrorsList, "User not found");
                    return(BadRequest(ErrorsList));
                }

                user.IsBlocked = isBlocked;

                ModelState.Clear();
                /// Try to validate the model
                if (!TryValidateModel(user))
                {
                    /// extract the errors and return bad request containing the errors
                    gAppConst.ExtractErrors(ModelState, ref ErrorsList);
                    return(BadRequest(ErrorsList));
                }

                /// update user in the context
                DbContext.Users.Update(user);

                /// save the changes to the database
                await DbContext.SaveChangesAsync().ConfigureAwait(false);

                /// thus return 200 ok status with the updated object
                return(Ok(user));
            }
            catch (Exception) // DbUpdateException, DbUpdateConcurrencyException
            {
                /// Add the error below to the error list and return bad request
                gAppConst.Error(ref ErrorsList, $"Server Issue. Please Contact Administrator.");
                return(BadRequest(ErrorsList));
            }
        }
        /// <summary>
        /// Moves the uploaded files to the avatar folder
        /// tus protocol puts the uploaded files into the store, XtraUpload move those files to the user directory
        /// </summary>
        private void MoveFilesToFolder(FileCompleteContext ctx, gUser user)
        {
            string userFolder   = Path.Combine(_uploadOpts.CurrentValue.UploadPath, user.Id);
            string avatarFolder = Path.Combine(userFolder, "avatar");

            // Create user root directory
            if (!Directory.Exists(userFolder))
            {
                Directory.CreateDirectory(userFolder);
            }
            // Creat avatar directory
            if (!Directory.Exists(avatarFolder))
            {
                Directory.CreateDirectory(avatarFolder);
            }
            // move avatar to the avatar folder
            DirectoryInfo directoryInfo = new DirectoryInfo(_uploadOpts.CurrentValue.UploadPath);

            foreach (FileInfo file in directoryInfo.GetFiles(ctx.FileId + "*"))
            {
                // Exemple of file names generated by tus are (...69375.metadata, ...69375.uploadlength ...)
                string[] subNames = file.Name.Split('.');
                string   subName  = subNames.Count() == 2 ? '.' + subNames[1] : "orig.avatar.png";
                File.Move(file.FullName, Path.Combine(avatarFolder, subName), true);
            }
            // crop image
            string avatarPath = Path.Combine(avatarFolder, "orig.avatar.png");

            using FileStream smallavatar = new FileStream(Path.Combine(avatarFolder, "avatar.png"), FileMode.Create);
            using Image image            = Image.Load(File.ReadAllBytes(avatarPath), out IImageFormat format);

            using Image smallthumbnail = image.Clone(i => i.Resize(128, 128).Crop(new Rectangle(0, 0, 128, 128)));
            smallthumbnail.Save(smallavatar, format);

            return;
        }
        [HttpPost("[action]")] /// Done
        public async Task <IActionResult> Login([FromBody] dynamic jsonData)
        {
            gAppConst.GetBrowserDetails(Request.Headers["User-Agent"].ToString(), out string BrowserName);
            bool         rememberMe;
            gUser        user;
            gLoginRecord loginRecord;

            try
            {
                /// extract the info from jsonData received
                user = new gUser
                {
                    Email        = jsonData.email,
                    PasswordHash = jsonData.password
                };
                loginRecord = new gLoginRecord
                {
                    BrowserName = BrowserName,
                };
                rememberMe = (bool)jsonData.rememberMe;
            }
            catch (Exception) /// catch error if jsonData is null
            {
                gAppConst.Error(ref ErrorsList, "Invalid Input. Please Contact Admin.");
                return(BadRequest(ErrorsList));
            }
            try
            {
                /// check if the email address exists. if not return bad request
                if (!DbContext.Users.Any(u => u.Email == user.Email))
                {
                    gAppConst.Error(ref ErrorsList, "Wrong Email.", "Email");
                    return(BadRequest(ErrorsList.ToArray()));
                }

                /// else user with the specified email is found. then get the user object from database
                gUser userDetails = DbContext.Users.Include(u => u.Department)
                                    .Include(u => u.Role)
                                    .Where(u => u.Email == user.Email)
                                    .FirstOrDefault();

                /// try to sign-in the user by using the password provided
                var loginResult = await authManager.PasswordSignInAsync(userDetails, user.PasswordHash, rememberMe, false).ConfigureAwait(false);

                /// if sign-in succeeded then return OK status
                if (loginResult.Succeeded)
                {
                    /// get the last login record
                    gLoginRecord LastLogin = null;
                    try
                    {
                        LastLogin = await DbContext.LoginRecords.LastAsync(l => l.UserId == userDetails.Id).ConfigureAwait(false);

                        /// If it is not the user's first login then populate the current users last login date property
                        if (LastLogin != null)
                        {
                            userDetails.LastLoginDate = LastLogin.TimeStamp;
                        }
                    }
                    catch (Exception) { }
                    loginRecord.UserId = userDetails.Id;
                    /// Add the login record and return the user's details
                    await DbContext.LoginRecords.AddAsync(loginRecord).ConfigureAwait(false);

                    await DbContext.SaveChangesAsync().ConfigureAwait(false);

                    return(Ok(userDetails));
                }

                /// else user has entered the wrong password
                gAppConst.Error(ref ErrorsList, "Wrong Password", "Password");
                return(BadRequest(ErrorsList));
            }
            catch (Exception eee)
            {
                /// if there are any exception return login failed error
                gAppConst.Error(ref ErrorsList, "Login Failed");
                return(BadRequest(ErrorsList));
            }
        }
Beispiel #11
0
        [Authorize(gAppConst.AccessPolicies.LevelOne)]  /// Done
        public async Task <IActionResult> Post([FromBody] gUser newUser)
        {
            try
            {
                newUser.PasswordHash = newUser.NewPassword;
                ModelState.Clear();
                /// if model validation failed
                if (!TryValidateModel(newUser))
                {
                    gAppConst.ExtractErrors(ModelState, ref ErrorsList);
                    /// return bad request with all the errors
                    return(BadRequest(ErrorsList));
                }

                /// check the database to see if a user with the same email exists
                if (await DbContext.Users.AnyAsync(d => d.Email == newUser.Email).ConfigureAwait(false))
                {
                    /// extract the errors and return bad request containing the errors
                    gAppConst.Error(ref ErrorsList, "Email already exists.");
                    return(BadRequest(ErrorsList));
                }
                newUser.Department = await DbContext.Departments.FindAsync(newUser.Department.Id).ConfigureAwait(false);

                newUser.Role = await DbContext.Roles.FindAsync(newUser.Role.Id).ConfigureAwait(false);

                /// else user object is made without any errors
                /// Create the new user
                IdentityResult newUserResult = await UserManager.CreateAsync(newUser, newUser.PasswordHash)
                                               .ConfigureAwait(false);


                /// If result failed
                if (!newUserResult.Succeeded)
                {
                    /// Add the error below to the error list and return bad request
                    foreach (var error in newUserResult.Errors)
                    {
                        gAppConst.Error(ref ErrorsList, error.Description, error.Code);
                    }
                    return(BadRequest(ErrorsList));
                }

                /// else result is successful the try to add the access claim for the user
                IdentityResult addedClaimResult = await UserManager.AddClaimAsync(
                    newUser,
                    new Claim(gAppConst.AccessClaims.Type, newUser.Role.AccessClaim)
                    ).ConfigureAwait(false);

                /// if claim failed to be created
                if (!addedClaimResult.Succeeded)
                {
                    /// remove the user account and return appropriate error
                    DbContext.Users.Remove(newUser);
                    await DbContext.SaveChangesAsync().ConfigureAwait(false);

                    gAppConst.Error(ref ErrorsList, "Server Issue. Please Contact Administrator.");
                    return(BadRequest(ErrorsList));
                }

                /// return 201 created status with the new object
                /// and success message
                return(Created("Success", newUser));
            }
            catch (Exception) // DbUpdateException, DbUpdateConcurrencyException
            {
                /// Add the error below to the error list and return bad request
                gAppConst.Error(ref ErrorsList, $"Server Issue. Please Contact Administrator.");
                return(BadRequest(ErrorsList));
            }
        }