Esempio n. 1
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var newUserName = model.FirstName.Trim() + "." + model.LastName.Trim();
            var user        = new MacheteUser {
                UserName = newUserName, LoweredUserName = newUserName.ToLower(), ApplicationId = GetApplicationId(), Email = model.Email.Trim(), LoweredEmail = model.Email.Trim()
            };
            var result = await _userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                // Nobody:
                // This comment: provide messaging to administrator to add appropriate roles to their account
                return(RedirectToAction("Index", "Home"));
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(error.Code, error.Description);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 2
0
        public async Task <ClaimsIdentity> GenerateClaimsIdentity(MacheteUser subject, JwtIssuerOptions jwtOptions)
        {
            var preferredUserName = $"{subject.FirstName} {subject.LastName}";

            if (string.IsNullOrWhiteSpace(preferredUserName))
            {
                preferredUserName = subject.UserName;
            }

            var claims = new List <Claim>
            {
                new Claim("id", subject.Id),
                new Claim(JwtRegisteredClaimNames.Iss, jwtOptions.Issuer),
                new Claim(JwtRegisteredClaimNames.Aud, jwtOptions.Audience),
                new Claim(JwtRegisteredClaimNames.Exp, UnixEpochDateFor(jwtOptions.Expiration)),
                new Claim(JwtRegisteredClaimNames.Nbf, UnixEpochDateFor(jwtOptions.NotBefore)),
                new Claim(JwtRegisteredClaimNames.Nonce, jwtOptions.Nonce),
                new Claim(JwtRegisteredClaimNames.Jti, await jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, UnixEpochDateFor(jwtOptions.IssuedAt)),
                //new Claim(JwtRegisteredClaimNames.AtHash, ???),
                //new Claim(JwtRegisteredClaimNames.Sid, ???),
                new Claim(JwtRegisteredClaimNames.Sub, subject.Id),
                new Claim(JwtRegisteredClaimNames.AuthTime, UnixEpochDateFor(jwtOptions.IssuedAt)),
                new Claim(JwtRegisteredClaimNames.Amr, "cookies") // TODO determine programatically
            };

            claims.AddRange(subject.UserRoles.Select(role => new Claim("role", role.Role.Name))); //TODO test
            claims.Add(new Claim("preferredUserName", preferredUserName));

            return(new ClaimsIdentity(new GenericIdentity(subject.UserName, "Token"), claims));
        }
Esempio n. 3
0
        // Enable initialization with an instance of ApplicationUser:
        public SelectUserRolesViewModel(MacheteUser userBeingModified,
                                        IEnumerable <MacheteRole> allRoles,
                                        UserManager <MacheteUser> userManager)
        {
            Roles    = new List <SelectRoleEditorViewModel>();
            UserName = userBeingModified.UserName;
            string[] firstLast = userBeingModified.UserName.Split('.');
            FirstName = firstLast[0];
            LastName  = firstLast.Length > 1 ? firstLast[1] : "";

            UserId = userBeingModified.Id;

            // ReSharper disable once SuggestVarOrType_Elsewhere
            // Add all available roles to the list of EditorViewModels:
            foreach (var role in allRoles)
            {
                // An EditorViewModel will be used by Editor Template:
                var selectableRole = new SelectRoleEditorViewModel(role);
                var isInRole       = userManager.IsInRoleAsync(userBeingModified, selectableRole.RoleName);
                isInRole.Wait(); // I'm sorry
                if (isInRole.Result)
                {
                    selectableRole.Selected = true;
                }
                Roles.Add(selectableRole);
            }
        }
Esempio n. 4
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                string      newUserName = model.FirstName.Trim() + "." + model.LastName.Trim();
                MacheteUser user        = new MacheteUser()
                {
                    UserName = newUserName, LoweredUserName = newUserName.ToLower(), ApplicationId = GetApplicationID(), Email = model.Email.Trim(), LoweredEmail = model.Email.Trim()
                };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // TODO: add user role to user & sign them in
                    // TODO: provide messaging to administrator to add appropriate roles to their account
                    //await SignInAsync(user, isPersistent: false);
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 5
0
        private async Task <IEnumerable <Claim> > GetClaimsFromAccount(MacheteUser user)
        {
            var claims = new List <Claim> {
                new Claim(Constants.ClaimTypes.Subject, user.Id.ToString()),
                new Claim(Constants.ClaimTypes.PreferredUserName, user.UserName),
            };

            if (userManager.SupportsUserEmail)
            {
                // GetEmailAsync is returning null; perhaps an overriden property in the base object
                // not sure, don't care.
                //var email = await userManager.GetEmailAsync(user.Id);
                if (!String.IsNullOrWhiteSpace(user.Email))
                {
                    claims.Add(new Claim(Constants.ClaimTypes.Email, user.Email));
                    var verified = await userManager.IsEmailConfirmedAsync(user.Id);

                    claims.Add(new Claim(Constants.ClaimTypes.EmailVerified, verified ? "true" : "false"));
                }
            }

            if (userManager.SupportsUserPhoneNumber)
            {
                var phone = await userManager.GetPhoneNumberAsync(user.Id);

                if (!String.IsNullOrWhiteSpace(phone))
                {
                    claims.Add(new Claim(Constants.ClaimTypes.PhoneNumber, phone));
                    var verified = await userManager.IsPhoneNumberConfirmedAsync(user.Id);

                    claims.Add(new Claim(Constants.ClaimTypes.PhoneNumberVerified, verified ? "true" : "false"));
                }
            }

            if (userManager.SupportsUserClaim)
            {
                claims.AddRange(await userManager.GetClaimsAsync(user.Id));
            }

            if (userManager.SupportsUserRole)
            {
                var roleClaims =
                    from role in await userManager.GetRolesAsync(user.Id)
                    select new Claim(Constants.ClaimTypes.Role, role);

                claims.AddRange(roleClaims);
            }

            if (!String.IsNullOrWhiteSpace(user.FirstName))
            {
                claims.Add(new Claim("given_name", user.FirstName));
            }
            if (!String.IsNullOrWhiteSpace(user.LastName))
            {
                claims.Add(new Claim("family_name", user.LastName));
            }
            return(claims);
        }
Esempio n. 6
0
        // Return a pre-populated instance of ApplicationUser:
        public MacheteUser GetUser()
        {
            var user = new MacheteUser
            {
                UserName = FirstName.Trim() + "." + LastName.Trim(),
                Email    = Email.Trim()
            };

            return(user);
        }
Esempio n. 7
0
        private async Task SignInAsync(MacheteUser user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            AuthenticationManager.SignIn(new AuthenticationProperties()
            {
                IsPersistent = isPersistent
            }, identity);
        }
Esempio n. 8
0
        // Return a pre-populated instance of ApplicationUser:
        public MacheteUser GetUser()
        {
            var user = new MacheteUser()
            {
                UserName = this.FirstName.Trim() + "." + this.LastName.Trim(),
                Email    = this.Email.Trim(),
            };

            return(user);
        }
Esempio n. 9
0
        public ActionResult Edit(string id, ManageMessageId?Message = null)
        {
            MacheteUser user = DatabaseFactory.Get().Users.First(u => u.Id == id);

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

            EditUserViewModel model = new EditUserViewModel(user);

            return(View(model));
        }
Esempio n. 10
0
        public ActionResult Edit(string id, ManageMessageId?Message = null)
        {
            MacheteUser user = _context.Users.First(u => u.Id == id);

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

            EditUserViewModel model = new EditUserViewModel(user);

            return(View(model));
        }
Esempio n. 11
0
        private async Task <IEnumerable <Claim> > GetClaimsForAuthenticateResult(MacheteUser user)
        {
            List <Claim> claims = new List <Claim>();

            if (EnableSecurityStamp && userManager.SupportsUserSecurityStamp)
            {
                var stamp = await userManager.GetSecurityStampAsync(user.Id);

                if (!String.IsNullOrWhiteSpace(stamp))
                {
                    claims.Add(new Claim("security_stamp", stamp));
                }
            }
            return(claims);
        }
Esempio n. 12
0
        private async Task <List <string> > TryChangePassword(MacheteUser user, string attemptedValue)
        {
            var errors = new List <string>();

            if (string.IsNullOrEmpty(attemptedValue))
            {
                return(new List <string>());
            }

            if (string.IsNullOrEmpty(user.PasswordHash))
            {
                errors.Add("This user's password is managed by another service.");
            }

            var remove = await _userManager.RemovePasswordAsync(user);

            if (!remove.Succeeded)
            {
                errors.Add("Something went wrong with your request. Contact an administrator for assistance.");
            }
            var result = await _userManager.AddPasswordAsync(user, attemptedValue);

            if (!result.Succeeded)
            {
                errors.Add("Something went wrong with your request. Contact an administrator for assistance.");
                foreach (var error in result.Errors)
                {
                    errors.Add(error.Description);
                    if (error.Description.Contains("is invalid, can only contain letters or digits") && user.UserName.Contains(" "))
                    {
                        ModelState.AddModelError("", ValidationStrings.NameHasSpace);
                    }
                }
            }

            if (errors.Any())
            {
                return(errors);
            }

            user.LastPasswordChangedDate = DateTime.Today.AddMonths(-PasswordExpirationInMonths);
            ViewBag.Message = "Password successfully updated.";

            return(new List <string>());
        }
Esempio n. 13
0
 // Allow Initialization with an instance of ApplicationUser:
 public EditUserViewModel(MacheteUser user)
 {
     UserName = user.UserName;
     string[] firstLast = user.UserName.Split('.');
     if (firstLast.Length == 2)
     {
         FirstName = firstLast[0];
         LastName  = firstLast[1];
     }
     else
     {
         FirstName = user.UserName;
         LastName  = "";
     }
     Email       = user.Email;
     IsApproved  = user.IsApproved;
     IsLockedOut = user.IsLockedOut;
     Id          = user.Id;
 }
Esempio n. 14
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new MacheteUser()
                {
                    UserName = model.FirstName + "." + model.LastName
                };
                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

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

                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
Esempio n. 15
0
        public static UserSettingsViewModel ToUserSettingsViewModel(this MacheteUser user, bool isHirer)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var userSettingsViewModel = new UserSettingsViewModel
            {
                ProviderUserKey = user.Id,
                UserName        = user.UserName,
                Email           = user.Email,
                IsApproved      = user.IsApproved ? "Yes" : "No",
                IsLockedOut     = user.IsLockedOut ? "Yes" : "No",
                IsOnline        = DbFunctions.DiffHours(user.LastLoginDate, DateTime.Now) < 1 ? "Yes" : "No",
                CreationDate    = user.CreateDate,
                LastLoginDate   = user.LastLoginDate,
                IsHirer         = isHirer
            };

            return(userSettingsViewModel);
        }
Esempio n. 16
0
        private async Task <List <string> > TryChangePassword(MacheteUser user, string attemptedValue)
        {
            var errors = new List <string>();

            if (string.IsNullOrEmpty(attemptedValue))
            {
                return(new List <string>());
            }

            if (string.IsNullOrEmpty(user.PasswordHash))
            {
                errors.Add("This user's password is managed by another service.");
            }

            var remove = await _userManager.RemovePasswordAsync(user);

            if (!remove.Succeeded)
            {
                errors.Add("Something went wrong with your request. Contact an administrator for assistance.");
            }

            var result = await _userManager.AddPasswordAsync(user, attemptedValue);

            if (!result.Succeeded)
            {
                errors.Add("Something went wrong with your request. Contact an administrator for assistance.");
            }

            if (errors.Any())
            {
                return(errors);
            }

            user.LastPasswordChangedDate = DateTime.Today.AddMonths(-PasswordExpirationInMonths);
            ViewBag.Message = "Password successfully updated.";

            return(new List <string>());
        }
Esempio n. 17
0
        // Enable initialization with an instance of ApplicationUser:
        public SelectUserRolesViewModel(MacheteUser user, MacheteContext dbFactory)
            : this()
        {
            UserName = user.UserName;
            string[] firstLast = user.UserName.Split('.');
            FirstName = firstLast[0];
            if (firstLast.Length > 1)
            {
                LastName = firstLast[1];
            }
            else
            {
                LastName = "";
            }

            UserId = user.Id;

            // ReSharper disable once SuggestVarOrType_Elsewhere
            // Add all available roles to the list of EditorViewModels:
            DbSet <IdentityRole> allRoles = dbFactory.Roles;

            foreach (var role in allRoles)
            {
                // An EditorViewModel will be used by Editor Template:
                var rvm = new SelectRoleEditorViewModel(role);
                Roles.Add(rvm);
            }

            // Set the Selected property to true for those roles for
            // which the current user is a member:
            foreach (var userRole in user.Roles)
            {
                SelectRoleEditorViewModel checkUserRole =
                    Roles.Find(r => r.RoleId == userRole.Id);
                checkUserRole.Selected = true;
            }
        }
Esempio n. 18
0
        // Enable initialization with an instance of ApplicationUser:
        public SelectUserRolesViewModel(MacheteUser user, IDatabaseFactory dbFactory)
            : this()
        {
            this.UserName = user.UserName;
            string[] firstLast = user.UserName.Split('.');
            this.FirstName = firstLast[0];
            if (firstLast.Length > 1)
            {
                this.LastName = firstLast[1];
            }
            else
            {
                this.LastName = "";
            }

            this.UserId = user.Id;

            // Add all available roles to the list of EditorViewModels:
            IDbSet <IdentityRole> allRoles = dbFactory.Get().Roles;

            foreach (var role in allRoles)
            {
                // An EditorViewModel will be used by Editor Template:
                var rvm = new SelectRoleEditorViewModel(role);
                this.Roles.Add(rvm);
            }

            // Set the Selected property to true for those roles for
            // which the current user is a member:
            foreach (IdentityUserRole userRole in user.Roles)
            {
                SelectRoleEditorViewModel checkUserRole =
                    this.Roles.Find(r => r.RoleId == userRole.RoleId);
                checkUserRole.Selected = true;
            }
        }
Esempio n. 19
0
        private Task <MacheteUser> InstantiateNewUserFromExternalProviderAsync(string provider, string providerId, IEnumerable <Claim> claims)
        {
            var    email = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.Email);
            var    name  = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.Name);
            string username;

            if (email == null)
            {
                throw new ArgumentException("Email claim must be present to create a new user");
            }

            username = email.Value;

            var user = new MacheteUser()
            {
                UserName        = username,
                LoweredUserName = username.ToLower(),
                Email           = email.Value,
                EmailConfirmed  = true,
                LoweredEmail    = email.Value.ToLower()
            };

            return(Task.FromResult(user));
        }
Esempio n. 20
0
 private bool HasPassword(MacheteUser user)
 {
     // Return whether user has a password hash
     return(user.PasswordHash != null);
 }
Esempio n. 21
0
 private bool IsInternalUser(MacheteUser user)
 {
     // Return whether user has a password hash
     return(user.UserName.Contains("@"));
 }
Esempio n. 22
0
 private Task <AuthenticateResult> PostAuthenticateLocalAsync(MacheteUser user, SignInMessage message)
 {
     return(Task.FromResult <AuthenticateResult>(null));
 }
Esempio n. 23
0
        private async Task <bool> SigninByEmailAsync(HttpResponseMessage tokenResponse, HttpClient httpClient, string provider, string redirectUri)
        {
            bool result = false;
            var  tokenResponseContent = tokenResponse.Content.ReadAsStringAsync();

            if (tokenResponse.IsSuccessStatusCode)
            {
                var tokenObject = JsonConvert.DeserializeObject <ExternalLoginAccessToken>(tokenResponseContent.Result);

                httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", tokenObject.access_token);

                string profileResponseUrl;
                switch (provider)
                {
                case "facebook":
                    profileResponseUrl = $"https://graph.facebook.com/me?" +
                                         $"fields=name,email&" +
                                         $"access_token={tokenObject.access_token}";
                    break;

                case "google":
                    // TODO we *should* get this URL from https://accounts.google.com/.well-known/openid-configuration
                    profileResponseUrl = "https://openidconnect.googleapis.com/v1/userinfo";
                    break;

                default:
                    throw new Exception("Unable to parse provider.");
                }

                var profileResponse = await httpClient.GetAsync(profileResponseUrl);

                var profileResponseContent = profileResponse.Content.ReadAsStringAsync();
                var profile = JsonConvert.DeserializeObject <ExternalLoginProfile>(profileResponseContent.Result);

                var validateProfile = profile.email != null;
                _logger.LogInformation($"{provider} login profile has a valid email?: {validateProfile}");
                if (!validateProfile)
                {
                    _logger.LogWarning($"{provider} login failed!: {provider} profile did not contain an email");
                    result = false;
                    return(result);
                }

                var user = await _userManager.FindByEmailAsync(profile.email);

                if (user == null)
                {
                    var name = profile.name?.Split(' ');
                    if (string.IsNullOrEmpty(profile.name))
                    {
                        name = new[] { "", "" }
                    }
                    ;

                    var macheteUser = new MacheteUser
                    {
                        UserName  = profile.email,
                        Email     = profile.email, // Machete pls
                        FirstName = name[0],
                        LastName  = name[1]        // Chaim pls
                    };
                    await _userManager.CreateAsync(macheteUser);

                    user = await _userManager.FindByEmailAsync(profile.email);

                    await _userManager.AddToRoleAsync(user, "Hirer");

                    /* **** me */
                }

                await VerifyClaimsExistFor(user.UserName);

                await _signinManager.SignInAsync(user, true);

                result = true;
            }
            else
            {
                throw new AuthenticationException(
                          $"Results: {tokenResponseContent.Result}\nRedirectUri: {redirectUri}\nRequest Scheme: {Environment.GetEnvironmentVariable("MACHETE_USE_HTTPS_SCHEME")}"
                          );
            }
            return(result);
        }