public ResultObj UpdateProfile(Profile profile)
        {
            ResultObj results;

            try
            {
                if (!IsValidProfile(profile))
                {
                    return(WebHelpers.BuildResponse(profile, "Role must have a name and at least one profile.", false, 1));
                }
                var oldRoles = new BaseRepository <Profile>().Get(profile.Id).Privileges.Split(',');
                var newRoles = profile.Privileges.Split(',');

                var users = _userRepo.Get(new UserFilter {
                    ProfileId = profile.Id
                });
                foreach (var user in users)
                {
                    UserManager.RemoveFromRoles(user.Id, oldRoles);
                    var user1 = user;
                    newRoles.ForEach(r => UserManager.AddToRole(user1.Id, r.Trim()));
                }

                new BaseRepository <Profile>().Update(profile);

                results = WebHelpers.BuildResponse(profile, "Role Update Successfully.", true, 1);
            }
            catch (Exception ex)
            {
                results = WebHelpers.ProcessException(ex);
            }

            return(results);
        }
        public ResultObj Logout()
        {
            var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;

            authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            return(WebHelpers.BuildResponse(new { }, "User Logged Out", true, 0));
        }
        public async Task <ResultObj> UpdateUser(UpdateUserModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(WebHelpers.ProcessException(ModelState.Values));
                }

                var user = _userRepo.Get(model.UserName);
                var role = new ProfileRepository().Get(model.RoleId);

                if (user == null)
                {
                    return(WebHelpers.BuildResponse(null, "Updating user not found. Please update an existing user", false, 0));
                }
                var oldRoles = user.Profile.Privileges.Split(',');

                user.ProfileId   = role.Id;
                user.Name        = model.Name;
                user.UpdatedAt   = DateTime.UtcNow;
                user.PhoneNumber = model.PhoneNumber;
                user.Email       = model.Email;
                _userRepo.Update(user);

                //Remove old reles
                oldRoles.ForEach(x => UserManager.RemoveFromRole(user.Id, x));

                //Add Roles in selected Role to user
                if (!string.IsNullOrEmpty(role.Privileges))
                {
                    role.Privileges.Split(',').ForEach(r => UserManager.AddToRole(user.Id, r.Trim()));
                }

                //Change Password
                if (!string.IsNullOrEmpty(model.Password))
                {
                    UserManager.RemovePassword(user.Id);
                    UserManager.AddPassword(user.Id, model.Password);
                }

                var data = new
                {
                    user.Id,
                    user.Name,
                    user.Email,
                    user.PhoneNumber,
                    user.UserName,
                    RoleId = user.ProfileId,
                    Role   = new { user.Profile.Id, user.Profile.Name },
                };

                return(WebHelpers.BuildResponse(data, "User Created Successfully", true, 1));
            }
            catch (Exception ex)
            {
                return(WebHelpers.ProcessException(ex));
            }
        }
Exemplo n.º 4
0
        public virtual ResultObj Get()
        {
            ResultObj results;

            try
            {
                var data = Repository.Get();
                results = WebHelpers.BuildResponse(data, "Records Loaded", true, data.Count());
            }
            catch (Exception ex)
            {
                results = WebHelpers.ProcessException(ex);
            }
            return(results);
        }
Exemplo n.º 5
0
        public virtual ResultObj Get(long id)
        {
            ResultObj results;

            try
            {
                var data = Repository.Get(id);
                results = WebHelpers.BuildResponse(data, "", true, 1);
            }
            catch (Exception ex)
            {
                results = WebHelpers.ProcessException(ex);
            }
            return(results);
        }
        public ResultObj GetRoles()
        {
            ResultObj results;

            try
            {
                var data = new AppDbContext().Roles.Select(x => x.Name).ToList();
                results = WebHelpers.BuildResponse(data, "", true, data.Count());
            }
            catch (Exception ex)
            {
                results = WebHelpers.ProcessException(ex);
            }
            return(results);
        }
        public async Task <ResultObj> Login(LoginModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("Please check the login details");
                }

                var user = await UserManager.FindAsync(model.UserName, model.Password);

                if (user == null)
                {
                    throw new Exception("Invalid Username or Password");
                }

                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

                authenticationManager.SignIn(new AuthenticationProperties {
                    IsPersistent = model.RememberMe
                }, identity);

                var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                var token  = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

                var data = new
                {
                    user.Id,
                    Username = user.UserName,
                    user.Name,
                    Role = new
                    {
                        user.Profile.Id,
                        user.Profile.Name,
                        Privileges = user.Profile.Privileges.Split(',')
                    },
                    token
                };

                return(WebHelpers.BuildResponse(data, "Login Successfull", true, 0));
            }
            catch (Exception e)
            {
                return(WebHelpers.ProcessException(e));
            }
        }
Exemplo n.º 8
0
        public virtual ResultObj Delete(long id)
        {
            ResultObj results;

            try
            {
                Repository.Delete(id);
                results = WebHelpers.BuildResponse(id, $"{_klassName} Deleted Successfully.", true, 1);
            }
            catch (Exception ex)
            {
                results = WebHelpers.ProcessException(ex);
            }

            return(results);
        }
        public ResultObj DeleteUser(string id)
        {
            ResultObj results;

            try
            {
                _userRepo.Delete(id);
                results = WebHelpers.BuildResponse(id, "User Deleted Successfully.", true, 1);
            }
            catch (Exception ex)
            {
                results = WebHelpers.ProcessException(ex);
            }

            return(results);
        }
Exemplo n.º 10
0
        public virtual ResultObj Put(T record)
        {
            ResultObj results;

            try
            {
                Repository.Update(SetAudit(record));

                results = WebHelpers.BuildResponse(record, $"{_klassName} Update Successfully.", true, 1);
            }
            catch (Exception ex)
            {
                results = WebHelpers.ProcessException(ex);
            }

            return(results);
        }
Exemplo n.º 11
0
        public virtual ResultObj Post(T record)
        {
            ResultObj results;

            try
            {
                Repository.Insert(SetAudit(record, true));

                results = WebHelpers.BuildResponse(record, $"New {_klassName} Saved Successfully.", true, 1);
            }
            catch (Exception ex)
            {
                results = WebHelpers.ProcessException(ex);
            }

            return(results);
        }
        public ResultObj Reset(string email)
        {
            try
            {
                using (var db = new AppDbContext())
                {
                    var existing = db.Users.FirstOrDefault(x => x.UserName == email && !x.Hidden && !x.Locked);
                    if (existing == null)
                    {
                        throw new Exception("Sorry email is not valid. Enjoy!!");
                    }
                    var newRecord = new ResetRequest
                    {
                        Email    = email,
                        Token    = StringHelpers.GenerateRandomString(32),
                        Date     = DateTime.Now,
                        Ip       = Request.Headers.Referrer.AbsoluteUri,
                        IsActive = true
                    };
                    db.ResetRequests.Add(newRecord);

                    // create a password reset entry
                    var link     = Request.Headers.Referrer.AbsoluteUri + "#/resetpassword/" + newRecord.Token;
                    var emailMsg = new EmailOutboxEntry
                    {
                        Message =
                            $"<h3>Password Reset Request</h3> <br/><br/> Please follow the link below to change your password. <br/><br/><b><a href='{link}'>Click here</a></b> to reset your password.<br/><br/><br/><br/>Please ignore this message if you did not make this request.<br/><br/>Thank you. <br/>",
                        Subject  = "Password Reset",
                        Sender   = "*****@*****.**",
                        Receiver = newRecord.Email,
                        Created  = DateTime.Now
                    };
                    db.EmailOutboxEntries.Add(emailMsg);
                    db.SaveChanges();
                    MessageHelpers.SendEmailMessage(emailMsg.Id);

                    return(WebHelpers.BuildResponse(null, "Password reset link has been sent to your email.", true, 1));
                }
            }
            catch (Exception e)
            {
                return(WebHelpers.ProcessException(e));
            }
        }
        public async Task <ResultObj> SignUp(RegisterBindingModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(WebHelpers.ProcessException(ModelState.Values));
                }
                var role = new ProfileRepository().Get(model.ProfileId);

                //Todo: Check Code Validation Somehow

                var user = new User
                {
                    UserName    = model.UserName,
                    ProfileId   = model.ProfileId,
                    Name        = model.Name,
                    PhoneNumber = model.PhoneNumber,
                    CreatedAt   = DateTime.UtcNow,
                    UpdatedAt   = DateTime.UtcNow
                };

                var identityResult = await UserManager.CreateAsync(user, model.Password);

                if (!identityResult.Succeeded)
                {
                    return(WebHelpers.ProcessException(identityResult));
                }


                //Add Roles in selected Role to user
                if (!string.IsNullOrEmpty(role.Privileges))
                {
                    role.Privileges.Split(',').ForEach(r => UserManager.AddToRole(user.Id, r.Trim()));
                }

                return(WebHelpers.BuildResponse(null, "Registration Successful", true, 1));
            }
            catch (Exception ex)
            {
                return(WebHelpers.ProcessException(ex));
            }
        }
        public async Task <ResultObj> ChangePassword(ChangePasswordBindingModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(WebHelpers.ProcessException(ModelState.Values));
                }

                var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(),
                                                                   model.OldPassword, model.NewPassword);

                return(!result.Succeeded ? WebHelpers.ProcessException(result)
                    : WebHelpers.BuildResponse(model, "Password changed sucessfully.", true, 1));
            }
            catch (Exception exception)
            {
                return(WebHelpers.ProcessException(exception));
            }
        }
        public ResultObj ResetPassword(ResetModel rm)
        {
            try
            {
                using (var db = new AppDbContext())
                {
                    var existing = db.ResetRequests.FirstOrDefault(x => x.Token == rm.Token && x.IsActive);
                    if (existing == null)
                    {
                        throw new Exception("Password reset was not complete");
                    }

                    var us = db.Users.FirstOrDefault(x => x.UserName == existing.Email && !x.Hidden && !x.IsDeleted);
                    if (us == null)
                    {
                        throw new Exception("System Error");
                    }
                    var result = UserManager.RemovePassword(us.Id);
                    if (result.Succeeded)
                    {
                        var res = UserManager.AddPassword(us.Id, rm.Password);
                        if (res.Succeeded)
                        {
                            existing.IsActive = false;
                        }
                        else
                        {
                            throw new Exception(string.Join(", ", res.Errors));
                        }
                    }
                    db.SaveChanges();
                    return(WebHelpers.BuildResponse(null, "Password Changed Successfully", true, 1));
                }
            }
            catch (Exception e)
            {
                return(WebHelpers.ProcessException(e));
            }
        }
 public ResultObj GetUsers()
 {
     try
     {
         var data = _userRepo.Get()
                    .Select(x => new
         {
             x.Id,
             x.Name,
             x.Email,
             x.PhoneNumber,
             x.UserName,
             RoleId = x.ProfileId,
             Role   = new { x.Profile.Id, x.Profile.Name }
         }).ToList();
         return(WebHelpers.BuildResponse(data, "", true, data.Count));
     }
     catch (Exception exception)
     {
         return(WebHelpers.ProcessException(exception));
     }
 }