Esempio n. 1
0
        //POST : /api/ApplicationUser/Register
        public async Task <Object> PostApplicationUser(ApplicationUserModel userModel)
        {
            var applicationUser = new ApplicationUser()
            {
                Email             = userModel.LoginEmail,
                FirstName         = userModel.FirstName,
                LastName          = userModel.LastName,
                UserName          = userModel.UserName,
                PhoneNumber       = userModel.PhoneNumber,
                SecurityProfileId = userModel.SecurityProfileId
            };

            try
            {
                var result = await _userManager.CreateAsync(applicationUser, userModel.Password);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //POST : /api/ApplicationUser/Register
        public async Task <object> PostApplicationUser(ApplicationUserModel model)
        {
            var applicationUser = new ApplicationUser()
            {
                UserName         = model.UserName,
                Email            = model.Email,
                FullName         = model.FullName,
                RegistrationDate = DateTime.UtcNow,
                LastLoginDate    = DateTime.UtcNow,
                IsBlocked        = false
            };

            try
            {
                var result = await userManager.CreateAsync(applicationUser, model.Password);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 3
0
        public async Task <IActionResult> RegisterUser([FromBody] ApplicationUserModel userData)
        {
            if (userData == null)
            {
                return(BadRequest());
            }

            try
            {
                var res = await userService.AddUser(userData);

                if (!res.Status)
                {
                    return(StatusCode(StatusCodes.Status401Unauthorized, res.Message));
                }

                return(Json(OperationActionResult.Success(res.Value)));
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
            }
        }
Esempio n. 4
0
        //POST : api/ApplicationUser/Register
        public async Task <Object> PostApplicationUser(ApplicationUserModel model)
        {
            var applicationUser = new ApplicationUser()
            {
                UserName         = model.UserName,
                Nume             = model.Nume,
                Prenume          = model.Prenume,
                ZiuaNastere      = model.ZiuaNastere,
                DataInregistrare = DateTime.Today,
                Notes            = model.Notes
            };

            try
            {
                var result = await _userManager.CreateAsync(applicationUser, model.Password);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 5
0
        //POST : /api/ApplicationUser/Register
        public async Task <Object> PostApplicationUser(ApplicationUserModel model)
        {
            var applicationUser = new ApplicationUser()
            {
                UserName  = model.UserName,
                Email     = model.Email,
                UserBasic = new UserBasicInfo()
                {
                    FullName = model.FullName
                }
            };

            try
            {
                var result = await _userManager.CreateAsync(applicationUser, model.Password);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 6
0
        //POST:api/ApplicationUser/Register

        public async Task <Object> PostApplicationUser(ApplicationUserModel model)
        {
            model.Role = "Admin";
            var applicationUser = new ApplicationUser()
            {
                UserName = model.UserName,
                Email    = model.Email,
                FullName = model.FullName,
            };

            try
            {
                var result = await _userManager.CreateAsync(applicationUser, model.Password);

                await _userManager.AddToRoleAsync(applicationUser, model.Role);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 7
0
        public async Task <Object> PostApplicationUser(ApplicationUserModel model)
        {
            model.Role = "Customer";
            var applicationUser = new ApplicationUser()
            {
                UserName = model.UserName,
                Email    = model.Email,
            };

            try
            {
                var result = await _userManager.CreateAsync(applicationUser, model.Password);

                await _userManager.AddToRoleAsync(applicationUser, model.Role);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                //Todo add logger ex
                return(StatusCode(500));
            }
        }
Esempio n. 8
0
        public List <ApplicationUserModel> GetAllUsers()
        {
            List <ApplicationUserModel> output = new List <ApplicationUserModel>();

            var users     = _context.Users.ToList();
            var userRoles = from ur in _context.UserRoles
                            join r in _context.Roles on ur.RoleId equals r.Id
                            select new { ur.UserId, ur.RoleId, r.Name };

            foreach (var user in users)
            {
                ApplicationUserModel u = new ApplicationUserModel
                {
                    Id    = user.Id,
                    Email = user.Email
                };

                u.Roles = userRoles.Where(x => x.UserId == u.Id).ToDictionary(key => key.RoleId, val => val.Name);

                output.Add(u);
            }
            return(output);
        }
Esempio n. 9
0
        public async Task <object> PostApplicationUser(ApplicationUserModel model)
        {
            var applicationUser = new ApplicationUser()
            {
                UserId    = model.UserId,
                UserName  = model.UserId,
                FirstName = model.FirstName,
                LastName  = model.LastName,
                Email     = model.Email,
                //   FullName = model.FullName
            };

            try
            {
                var result = await _userManager.CreateAsync(applicationUser, model.Password);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        // POST request :: /api/ApplicationUser/Register
        public async Task <Object> PostApplicationUser(ApplicationUserModel model)
        {
            model.Role = "Viewer";
            var applicationUser = new ApplicationUser()
            {
                UserName  = model.UserName,
                Email     = model.Email,
                FirstName = model.FirstName,
                LastName  = model.LastName      // Password will be encrypted that's why not mentioned here...
            };

            try
            {
                var result = await userManager.CreateAsync(applicationUser, model.Password);  /// Password will be encrypted

                await userManager.AddToRoleAsync(applicationUser, model.Role);

                return(Ok(result));
            } catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 11
0
        //POST : /api/User/Register
        public async Task <Object> PostUser(ApplicationUserModel model)
        {
            //model.Role = "Customer";
            model.Role = "Admin";
            var user = new ApplicationUser();

            user.UserName = model.UserName;
            user.Email    = model.Email;
            user.FullName = model.FullName;

            try
            {
                var res = await _userManager.CreateAsync(user, model.Password);

                await _userManager.AddToRoleAsync(user, model.Role);

                return(Ok(res));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 12
0
        public ApplicationUserModel UpdateUser(string userId, ApplicationUserModel userModel)
        {
            List <string> errorMessage = null;

            if (!userModel.IsValid(out errorMessage))
            {
                throw new ArgumentException("userModel", String.Join("; ", errorMessage));
            }

            var user = _context.Users
                       .Where(x => x.Id == userId)
                       .FirstOrDefault();

            if (user == null)
            {
                throw new ApplicationException(String.Format("User with id {0} does not exist", userModel.Id));
            }

            user = userModel.MapApplicationUserModelToApplicationUser(user);

            _context.SaveChanges();
            return(user.MapApplicationUserToApplicationUserModel());
        }
Esempio n. 13
0
        //POST : /api/ApplicationUser/CreateUser
        public IActionResult PostApplicationUser(ApplicationUserModel model)
        {
            _uow.SetActiveUserId(Int32.Parse(Request.Headers["CurrentUserId"]));
            //We need to determine if this is an add or update action


            var applicationUser = model.Id != 0 ? _uow.Users.SingleOrDefault(u => u.Id == model.Id) : new User();


            applicationUser.UserName     = model.UserName;
            applicationUser.Email        = model.Email;
            applicationUser.FirstName    = model.FirstName;
            applicationUser.LastName     = model.LastName;
            applicationUser.PasswordHash = model.Id.HasValue ? Cipher.Encrypt(model.Password, Cipher.orionSalt) : applicationUser.PasswordHash;
            applicationUser.ChangePasswordOnNextLogin = model.ChangePasswordOnNextLogin;
            applicationUser.EmployeeNumber            = model.EmployeeNumber;
            applicationUser.IsActive        = model.IsActive;
            applicationUser.LockoutEnabled  = model.LockoutEnabled;
            applicationUser.AppointmentDate = DateTime.Today;
            applicationUser.RoleId          = model.RoleId;
            applicationUser.AccessGroupId   = model.AccessGroupId;


            try
            {
                if (model.Id == 0)
                {
                    _uow.Users.Add(applicationUser);
                }
                _uow.Complete();
                return(Ok());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 14
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUserModel
                {
                    UserName       = model.Email,
                    Email          = model.Email,
                    DrivingLicense = model.DrivingLicense,
                    PhoneNr        = model.PhoneNr,
                    Name           = model.Name
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Home"));

                    //var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
                    //var roleManager = new RoleManager<IdentityRole>(roleStore);
                    //await roleManager.CreateAsync(new IdentityRole("CanManageMovies"));
                    //await UserManager.AddToRoleAsync(user.Id, "CanManageMovies");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 15
0
        public async Task <Result <AuthorizeResponseModel> > Authorize(ApplicationUserModel model)
        {
            try
            {
                var hashedPassword = CryptographyHelper.Hash(model.Password, HASHKEY + model.Email);
                var user           = await _userRepository.GetSingle(u => u.Email == model.Email && u.HashedPassword == hashedPassword);

                if (user != null)
                {
                    user.LastLogin = DateTime.Now;
                    _userRepository.Update(user);
                    var role = await GetRole(model.Email);

                    string encodedJwt = await GetJWTToken(model, role);

                    user.LastLogin = DateTime.Now;

                    var response = new AuthorizeResponseModel()
                    {
                        AccessToken = encodedJwt,
                        Expires     = (int)_jwtOptions.ValidFor.TotalSeconds
                    };

                    return(new Result <AuthorizeResponseModel>(response));
                }
                else
                {
                    ErrorResult error = GenerateError("User not found", "Email", "Invalid email", ErrorStatus.ObjectNotFound);
                    return(new Result <AuthorizeResponseModel>(error));
                }
            }
            catch (Exception ex)
            {
                ErrorResult error = GenerateError(ex);
                return(new Result <AuthorizeResponseModel>(error));
            }
        }
Esempio n. 16
0
        public async Task <IActionResult> Login(ApplicationUserModel model)
        {
            var user = await _userManager.FindByNameAsync(model.Username);

            if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
            {
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim("UserID", user.Id.ToString())
                    }),
                    Expires            = DateTime.UtcNow.AddDays(1),
                    SigningCredentials = new SigningCredentials(new
                                                                SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.Secret)),
                                                                SecurityAlgorithms.HmacSha256Signature)
                };

                var tokenHandler = new JwtSecurityTokenHandler();

                var securityToken = tokenHandler.CreateToken(tokenDescriptor);

                var token = tokenHandler.WriteToken(securityToken);

                return(Ok(new
                {
                    id = user.Id,
                    username = user.UserName,
                    email = user.Email,
                    token = token
                }));
            }
            else
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }
        }
        //POST : /api/ApplicationUser/Register
        public async Task <Object> PostApplicationUser(ApplicationUserModel model)
        {
            ApplicationUser user;

            if (model.Role == "Menjacnica")
            {
                user = new ExchangeOfficer();
                if (model.Longitude.HasValue && model.Latitude.HasValue)
                {
                    var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326);
                    (user as ExchangeOfficer).Location = geometryFactory.CreatePoint(new Coordinate(model.Longitude.Value, model.Latitude.Value));
                    (user as ExchangeOfficer).Address  = model.Address;
                }
            }
            else
            {
                user = new ExchangeCustomer();
            }

            user.UserName = model.UserName;
            user.Email    = model.Email;
            user.FullName = model.FullName;

            try
            {
                var result = await userManager.CreateAsync(user, model.Password);

                await userManager.AddToRoleAsync(user, model.Role);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            ApplicationUserModel user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                  CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Esempio n. 19
0
        //POST : api/ApplicationUser/Register
        public async Task <Object> PostApplicationUser(ApplicationUserModel model)
        {
            model.Role = "Customer";
            var applicationUser = new ApplicationUser()
            {
                UserName          = model.UserName,
                Email             = model.Email,
                FullName          = model.FullName,
                MaxCharacterCount = _appSettings.Max_Character_Count
            };

            try
            {
                var result = await _userManager.CreateAsync(applicationUser, model.Password);

                await _userManager.AddToRoleAsync(applicationUser, model.Role);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //POST: /api/ApplicationUser/Register


        public async Task <Object> PostApplicationUser(ApplicationUserModel model)
        {
            var applicationUser = new ApplicationUser()
            {
                Title         = model.Title,
                FirstName     = model.FirstName,
                LastName      = model.LastName,
                Gender        = model.Gender,
                UserName      = model.UserName,
                Discriminator = model.Discriminator,
                Email         = model.Email
            };

            try
            {
                var result = await _usermanager.CreateAsync(applicationUser, model.Password);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 21
0
        //POST: /api/AdminPanel/AddNewUser
        public async Task <Object> UpdateUser(ApplicationUserModel model)
        {
            var changeUser = await _userManager.FindByEmailAsync(model.Email);

            changeUser.Email        = model.Email;
            changeUser.Name         = model.FullName;
            changeUser.UserName     = model.UserName;
            changeUser.PasswordHash = model.Password;

            await _userManager.UpdateAsync(changeUser);

            var users = _userManager.Users.Select(u =>
                                                  new
            {
                Email    = u.Email,
                Name     = u.UserName,
                UserName = u.UserName,
                Password = u.PasswordHash
            });



            return(Ok(users));
        }
Esempio n. 22
0
        public List <ApplicationUserModel> GetAllUsers()
        {
            List <ApplicationUserModel> output = new List <ApplicationUserModel>();

            using (var context = new ApplicationDbContext())
            {
                var userStore   = new UserStore <ApplicationUser>(context);
                var userManager = new UserManager <ApplicationUser>(userStore);

                var users = userManager.Users.ToList();
                var roles = context.Roles.ToList();

                foreach (var user in users)
                {
                    //UserData data = new UserData();

                    var userInfo = _data.GetUserById(user.Id).First();

                    ApplicationUserModel u = new ApplicationUserModel
                    {
                        Id        = user.Id,
                        Email     = user.Email,
                        FirstName = userInfo.FirstName,
                        LastName  = userInfo.LastName
                    };

                    foreach (var r in user.Roles)
                    {
                        u.Roles.Add(r.RoleId, roles.Where(x => x.Id == r.RoleId).First().Name);
                    }
                    output.Add(u);
                }
            }

            return(output);
        }
Esempio n. 23
0
        public async Task <object> Login([FromBody] ApplicationUserModel applicationUserModel)
        {
            var result = await _signInManager.PasswordSignInAsync(applicationUserModel.Email, applicationUserModel.Password, false, false);

            var resultModel = new ResultModel();

            if (!result.Succeeded)
            {
                return(BadRequest(resultModel));
            }
            var appUser = _userManager.Users.SingleOrDefault(r => r.Email == applicationUserModel.Email);
            var role    = _userManager.GetRolesAsync(appUser).Result.FirstOrDefault();

            if (appUser == null)
            {
                return(Ok(resultModel));
            }
            resultModel.Fio          = appUser.Fio;
            resultModel.Role         = role;
            resultModel.ResultStatus = result.Succeeded;
            resultModel.Token        = (string)GenerateJwtToken(applicationUserModel.Email, appUser);

            return(Ok(resultModel));
        }
Esempio n. 24
0
        //Get : /api/UserAccount
        public async Task <IActionResult> GetUserAccount()
        {
            string userId = User.Claims.First(x => x.Type == "UserID").Value;
            var    user   = await _userManager.FindByIdAsync(userId);

            var roles = await _userManager.GetRolesAsync(user);

            var applicationUser = new ApplicationUserModel
            {
                ID        = user.Id,
                FirstName = user.FirstName,
                LastName  = user.LastName,
                Email     = user.Email,
                UserName  = user.UserName,
                Address   = user.Address,
                City      = user.City,
                State     = user.State,
                Zip       = user.Zip,
                About     = user.About,
                Role      = roles.FirstOrDefault()
            };

            return(Ok(applicationUser));
        }
Esempio n. 25
0
        public IEnumerable <ApplicationUserModel> GetUserDetailsPerPage(int page, int pageSize)
        {
            var users = _userManager.Users.Skip((page - 1) * pageSize)
                        .Take(pageSize)
                        .ToList();

            var usersResultList = new List <ApplicationUserModel>();

            users.ForEach(user =>
            {
                var userRoleIds = _context.UserRoles.Where(x => x.UserId == user.Id)
                                  .Select(y => y.RoleId).ToList();

                var roles = _context.Roles.Where(x => userRoleIds.Contains(x.Id)).ToList();

                roles.ForEach(role =>
                {
                    //var res = new ApplicationUserModel();
                    var res = new ApplicationUserModel
                    {
                        Id        = user.Id,
                        FirstName = user.FirstName,
                        LastName  = user.LastName,
                        Email     = user.Email,
                        //var listOfRoles = _userManager.GetRolesAsync(user);
                        Role = role.Name,
                    };

                    usersResultList.Add(res);
                });
            });
            //var listOfRoles = await _userManager.GetRolesAsync(users[0]).GetAwaiter();
            //var listOfRoles = _userManager.GetRolesAsync(users[0]);

            return(usersResultList);
        }
        public async Task <ActionResult> CreateApplicationUser(ApplicationUserModel model)
        {
            var applicationUser = new ApplicationUser
            {
                UserName = model.UserName,
                Email    = model.Email,
                FullName = model.FullName
            };

            model.Role = "Customer";

            try
            {
                var result = await this.userManager.CreateAsync(applicationUser, model.Password);

                await this.userManager.AddToRoleAsync(applicationUser, model.Role);

                return(Ok(result));
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        //POST : /api/ApplicationUser/mentor
        public async Task <Object> PostMentor(ApplicationUserModel model)
        {
            //The role assigned when a new member signs up
            model.Role = "Mentor";
            var applicationUser = new ApplicationUser()
            {
                UserName = model.UserName,
                Email    = model.Email,
                FullName = model.FullName
            };

            try
            {
                var result = await _userManager.CreateAsync(applicationUser, model.Password);

                await _userManager.AddToRoleAsync(applicationUser, model.Role);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 28
0
        public async Task <ApplicationUserModel> SearchByEmail(string email)
        {
            var user = await _userManager.FindByNameAsync(email);

            if (user == null)
            {
                return(null);
            }

            var userRoles = from ur in _context.UserRoles
                            join r in _context.Roles on ur.RoleId equals r.Id
                            select new { ur.UserId, ur.RoleId, r.Name };

            ApplicationUserModel u = new ApplicationUserModel
            {
                Id    = user.Id,
                Email = user.Email
            };

            u.Roles = userRoles.Where(x => x.UserId == u.Id).ToDictionary(key => key.RoleId, val => val.Name);


            return(u);
        }
Esempio n. 29
0
        //POST : /api/ApplicationUser/Register
        public async Task <Object> PostApplicationUser(ApplicationUserModel model)
        {
            var applicationUser = new ApplicationUser()
            {
                Id          = model.Email,
                UserName    = model.Email,
                Email       = model.Email,
                Name        = model.Name,
                PhoneNumber = "0",
                BornDate    = model.BornDate,
                Sex         = model.Sex,
            };

            try
            {
                var result = await _userManager.CreateAsync(applicationUser, model.Password);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
        public static bool IsValid(this ApplicationUserModel userModel, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Regex r = new Regex("^[a-zšđčćž A-ZŠĐČĆŽ]+$");

            //"^[a - zšđčćž A - ZŠĐČĆŽ] +$/gi"

            if (userModel == null)
            {
                errorMessages.Add("User model cannot be null.");

                return(false);
            }


            if (!String.IsNullOrWhiteSpace(userModel.FirstName))
            {
                if (!r.IsMatch(userModel.FirstName))
                {
                    errorMessages.Add("User can only have letters in  firstname");
                }
            }

            if (!String.IsNullOrWhiteSpace(userModel.LastName))
            {
                if (!r.IsMatch(userModel.LastName))
                {
                    errorMessages.Add("Users can only have letters in lastname");
                }
            }

            if (String.IsNullOrWhiteSpace(userModel.FirstName))
            {
                errorMessages.Add("User must have first name.");
            }

            if (String.IsNullOrWhiteSpace(userModel.LastName))
            {
                errorMessages.Add("User must have last name.");
            }

            if (userModel.JobTitleId <= 0)
            {
                errorMessages.Add("User must have title id.");
            }

            if (userModel.JobPositionId <= 0)
            {
                errorMessages.Add("User must have positon id.");
            }

            if (userModel.ManagerId != null)
            {
                if (userModel.ReviewerId == null)
                {
                    errorMessages.Add("User must have reviewer id.");
                }

                if (userModel.TemplateId == null)
                {
                    errorMessages.Add("User must have template id.");
                }
            }
            if (userModel.EmploymentDate.Equals(DateTime.MinValue))
            {
                errorMessages.Add("User must have Employment date");
            }

            return(errorMessages.Count == 0);
        }