Exemplo n.º 1
0
 private void ChangePassword(UserMembershipProvider provider, UserProfileModel profile)
 {
     if (profile.Password != null &&
         !provider.ChangePassword(profile.Username, profile.PreviousPassword, profile.Password))
     {
         ModelState.AddModelError("PreviousPassword", "Неправильный пароль");
     }
 }
Exemplo n.º 2
0
        public ActionResult Facebook(string code)
        {
            const string fbRedirectPath = "oauthconsent/facebook";
            string       uriTemplate    = "https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}";

            var    requestUrl      = this.HttpContext.Request.Url;
            var    redirectUrl     = string.Format("{0}://{1}/{2}", requestUrl.Scheme, requestUrl.Authority, fbRedirectPath);
            string encodedRedirect = HttpUtility.UrlEncode(redirectUrl);
            string uri             = string.Format(uriTemplate, FBAppID, encodedRedirect, FBAppSecret, code);

            WebRequest  req  = WebRequest.Create(uri);
            WebResponse resp = req.GetResponse();

            string   token   = null;
            DateTime?expires = null;

            using (Stream stream = resp.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    string data = reader.ReadToEnd();

                    string[] parts = data.Split('&');
                    foreach (var s in parts)
                    {
                        string[] kv = s.Split('=');
                        if (kv[0].Equals("access_token", StringComparison.Ordinal))
                        {
                            token = kv[1];
                        }
                        else if (kv[0].Equals("expires"))
                        {
                            expires = DateTime.UtcNow.AddSeconds(int.Parse(kv[1]));
                        }
                    }
                }

            var renewed = false;

            try
            {   // store token
                renewed = UserMembershipProvider.SaveCredential(this.CurrentUser.Name, UserCredential.FacebookConsent, token, expires);
            }
            catch (Exception ex)
            {
                TraceLog.TraceException("Failed to store Facebook consent token for User", ex);
                return(RedirectToAction("Home", "Dashboard", new { consentStatus = UserDataModel.FBConsentFail }));
            }
            if (renewed)
            {
                return(RedirectToAction("Home", "Dashboard"));
            }
            else
            {
                return(RedirectToAction("Home", "Dashboard", new { consentStatus = UserDataModel.FBConsentSuccess }));
            }
        }
Exemplo n.º 3
0
        public ActionResult LoginPost(string redirectUrl, Login model)
        {
            ViewBag.redirectUrl = redirectUrl;
            if (ModelState.IsValid)
            {
                UserMembershipProvider mp = new UserMembershipProvider();
                if (mp.ValidateUser(model.Email, model.Password))
                {
                    System.Web.HttpContext.Current.Session["Email"] = model.Email;

                    var users = Adapter.UserRepository.Find(a => a.Email == model.Email, null);
                    if (users != null && users.Any())
                    {
                        User user = users.First();
                        if (user.ApprovedDate == null)
                        {
                            ModelState.AddModelError("", "Je hebt je profiel nog niet geactiveerd met de activatielink in de e-mail.");
                            return(View(model));
                        }
                        if (user.LockedDate != null)
                        {
                            ModelState.AddModelError("", "Een administrator heeft je profiel gelockt. Gelieve contact op te nemen met onze support.");
                            return(View(model));
                        }

                        user.CreatedDate = DateTime.UtcNow;
                        Adapter.UserRepository.Update(user);
                        Adapter.Save();


                        HttpCookie cookie = new HttpCookie("RadarEmail", model.Email);
                        this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
                        HttpCookie cookieP = new HttpCookie("RadarPassword", user.Password);
                        this.ControllerContext.HttpContext.Response.Cookies.Add(cookieP);

                        if (!String.IsNullOrEmpty(redirectUrl))
                        {
                            byte[] b   = Convert.FromBase64String(redirectUrl);
                            string url = System.Text.Encoding.UTF8.GetString(b);
                            return(Redirect(url + "?&message=login"));
                        }
                        else
                        {
                            return(Redirect("http://localhost:4911/Radar/app/#/?message=login"));
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Het emailadres of het paswoord is niet geldig.");
                }
            }
            return(View(model));
        }
Exemplo n.º 4
0
        protected HttpStatusCode AuthenticateUser(HttpRequestMessage req)
        {
            TraceLog.TraceFunction();

            // this should work if auth cookie has been provided
            MembershipUser mu = Membership.GetUser();

            if (mu != null && Membership.Provider is UserMembershipProvider)
            {   // get user id from authenticated identity (cookie)
                this.currentUser = UserMembershipProvider.AsUser(mu);
                return(HttpStatusCode.OK);
            }

            BasicAuthCredentials credentials = GetUserFromMessageHeaders(req);

            if (credentials == null)
            {
                if (HttpContext.Current.Request.Headers[authRequestHeader] != null)
                {   // cookie is no longer valid, return 401 Unauthorized
                    TraceLog.TraceError("Cookie is expired or invalid");
                    return(HttpStatusCode.Unauthorized);
                }

                // auth headers not found, return 400 Bad Request
                TraceLog.TraceError("Bad request: no user information found");
                return(HttpStatusCode.BadRequest);
            }

            try
            {   // authenticate the user
                if (Membership.ValidateUser(credentials.Name, credentials.Password) == false)
                {
                    TraceLog.TraceError("Invalid username or password for user " + credentials.Name);
                    return(HttpStatusCode.Forbidden);
                }

                mu = Membership.GetUser(credentials.Name, true);
                this.currentUser = UserMembershipProvider.AsUser(mu);

                if (Membership.Provider is UserMembershipProvider)
                {   // add auth cookie to response (cookie includes user id)
                    HttpCookie authCookie = UserMembershipProvider.CreateAuthCookie(this.currentUser);
                    HttpContext.Current.Response.Cookies.Add(authCookie);
                }

                TraceLog.TraceInfo(String.Format("User {0} successfully logged in", credentials.Name));
                return(HttpStatusCode.OK);
            }
            catch (Exception ex)
            {   // username not found - return 404 Not Found
                TraceLog.TraceException(String.Format("Username not found: {0}", credentials.Name), ex);
                return(HttpStatusCode.NotFound);
            }
        }
        /// <summary>
        /// Implement to include authentication logic and create IPrincipal
        /// </summary>
        protected override bool TryCreatePrincipal(string email, string password, out RadarPrincipal principal)
        {
            principal = null;
            var mem = new UserMembershipProvider();

            if (!mem.ValidateUserEncoded(email, password))
            {
                return(false);
            }
            principal = new RadarPrincipal(new RadarIdentity(email, "Basic"));
            return(true);
        }
Exemplo n.º 6
0
        public ActionResult EditProfile(UserProfileModel profile, List <string> role)
        {
            if (ModelState.IsValid)
            {
                if (profile == null)
                {
                    throw new HttpException(404, "Not Found");
                }

                var  provider      = new UserMembershipProvider(userService, avatarService, roleService);
                bool isNameChanged = false;

                try
                {
                    if (User.IsInRole("admin"))
                    {
                        isNameChanged = ChangeUsername(provider, profile);
                        provider.ChangeEmail(profile.Username, profile.Email);
                        SetRoles(profile, role);
                    }
                    else
                    {
                        profile.Username = profile.PreviousUsername;
                    }

                    ChangeAvatar(provider, profile);
                    ChangePassword(provider, profile);


                    if (ModelState.IsValid)
                    {
                        TempData["MessageType"]         = MessageType.success;
                        TempData["StrongResultMessage"] = "Изменения сохранены";

                        if (isNameChanged && User.Identity.Name == profile.PreviousUsername)
                        {
                            return(RedirectToAction("Logout", "Account"));
                        }
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                catch (Exception)
                {
                    TempData["MessageType"]         = MessageType.error;
                    TempData["StrongResultMessage"] = "Произошла ошибка во время сохранения изменений!";
                    TempData["ResultMessage"]       = "Некоторые данные могут быть не сохранены";
                    return(RedirectToAction("Index", "Home"));
                }
            }
            return(View(profile));
        }
Exemplo n.º 7
0
 private void SetAuthCookie(string username, bool persistent)
 {
     if (Membership.Provider is UserMembershipProvider)
     {
         User user = new User {
             Name = username
         };
         HttpCookie authCookie = UserMembershipProvider.CreateAuthCookie(user, out this.renewFBToken);
         this.Response.Cookies.Add(authCookie);
     }
     else
     {
         FormsAuthentication.SetAuthCookie(username, persistent);
     }
 }
Exemplo n.º 8
0
 private bool ChangeUsername(UserMembershipProvider provider, UserProfileModel profile)
 {
     if (profile.PreviousUsername != profile.Username && !string.IsNullOrEmpty(profile.Username))
     {
         if (!provider.IsUsernameExist(profile.Username))
         {
             provider.ChangeUsername(profile.PreviousUsername, profile.Username);
             return(true);
         }
         else
         {
             ModelState.AddModelError("Username", "Такое имя пользователя уже существует");
         }
     }
     return(false);
 }
Exemplo n.º 9
0
    protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var authHeader = request.Headers.Authorization;

        if (authHeader == null)
        {
            return(base.SendAsync(request, cancellationToken));
        }

        if (authHeader.Scheme != "Basic")
        {
            return(base.SendAsync(request, cancellationToken));
        }

        if (String.IsNullOrEmpty(authHeader.Parameter))
        {
            return(base.SendAsync(request, cancellationToken));
        }

        var encodedUserPass = authHeader.Parameter.Trim();
        var userPass        = Encoding.ASCII.GetString(Convert.FromBase64String(encodedUserPass));
        var parts           = userPass.Split(":".ToCharArray());
        var email           = parts[0];
        var password        = parts[1];
        var mem             = new UserMembershipProvider();

        if (!mem.ValidateUserEncoded(email, password))
        {
            return(base.SendAsync(request, cancellationToken));
        }

        var i = new RadarIdentity(email, "Basic");
        //var identity = new GenericIdentity(username, "Basic");

        //string[] roles = RadarRoleProvider.GetRolesForUser(email);
        var p = new RadarPrincipal(i);

        //var principal = new GenericPrincipal(i, roles);
        Thread.CurrentPrincipal = p;

        if (HttpContext.Current != null)
        {
            HttpContext.Current.User = p;
        }

        return(base.SendAsync(request, cancellationToken));
    }
Exemplo n.º 10
0
 private void ChangeAvatar(UserMembershipProvider provider, UserProfileModel profile)
 {
     if (profile.AvatarFile != null)
     {
         if (profile.AvatarFile.ContentLength < RegisterUserModel.maxAvatarSize)
         {
             provider.ChangeUserAvatar(profile.AvatarFile, profile.UserId);
             Session["Avatar"] = null;
         }
         else
         {
             ModelState.AddModelError("AvatarFile",
                                      String.Format("Размер аватара не может превышать {0} МБ",
                                                    RegisterUserModel.maxAvatarSize / (1024 * 1024)));
         }
     }
 }
Exemplo n.º 11
0
 public ActionResult Login(LoginModel model)
 {
     if (ModelState.IsValid)
     {
         UserMembershipProvider mp = new UserMembershipProvider();
         if (mp.ValidateUser(model.Email, model.Password))
         {
             FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
             return(RedirectToAction("Index", "Home"));
         }
         else
         {
             ModelState.AddModelError("", "De gebruikersnaam of het wachtwoord is niet correct.");
         }
     }
     return(View(model));
 }
Exemplo n.º 12
0
        public ActionResult RegisterPost(Register model, string redirectUrl)
        {
            ViewBag.redirectUrl = redirectUrl;
            if (ModelState.IsValid)
            {
                var userModel            = model;
                RadarModels.Location loc = new RadarModels.Location();
                loc.Street  = model.Location.Street;
                loc.Number  = model.Location.Number;
                loc.Box     = model.Location.Box;
                loc.Zipcode = model.Location.Zipcode;
                loc.City    = model.Location.City;
                loc.Country = model.Location.Country;
                IGeocoder geocoder  = new GoogleGeocoder();
                Address[] addresses = geocoder.Geocode(loc.Street + " " + loc.Number + ", " + loc.Zipcode + " " + loc.City + ", " + loc.Country).ToArray();
                if (addresses.Length != 0 && addresses[0].Coordinates != null)
                {
                    loc.Latitude  = Convert.ToDecimal(addresses[0].Coordinates.Latitude);
                    loc.Longitude = Convert.ToDecimal(addresses[0].Coordinates.Longitude);
                    Adapter.LocationRepository.Insert(loc);
                    Adapter.Save();
                }
                else
                {
                    ModelState.AddModelError("", "Het adres kon niet worden gevonden.");
                    return(View(model));
                }


                UserMembershipProvider mp = new UserMembershipProvider();

                MembershipCreateStatus status;

                UserMembershipUser mu = mp.CreateUserBetter(model.Username, model.Email, model.Gender?"m":"f", model.Password, model.DateOfBirth, model.Bio, loc.LocationId, out status) as UserMembershipUser;

                if (status == MembershipCreateStatus.DuplicateEmail)
                {
                    ModelState.AddModelError("", "Emailadres heeft al een account.");
                }
                else if (status == MembershipCreateStatus.InvalidPassword)
                {
                    ModelState.AddModelError("", "Paswoord is niet sterk genoeg. Moet minimum 5 karakters zijn.");
                }
                else if (status == MembershipCreateStatus.Success)
                {
                    SendMail(userModel);

                    if (!String.IsNullOrEmpty(redirectUrl))
                    {
                        byte[] b   = Convert.FromBase64String(redirectUrl);
                        string url = System.Text.Encoding.UTF8.GetString(b);
                        return(Redirect(url + "?&message=registered"));
                    }
                    else
                    {
                        return(Redirect("http://localhost:4911/Radar/app/#/?message=registered"));
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "De ingevulde gegevens zijn niet correct.");
            }
            return(View(model));
        }
Exemplo n.º 13
0
 public AccountController(IUserService userService, IAvatarService avatarService, IRoleService roleService)
 {
     membershipProvider = new UserMembershipProvider(userService, avatarService, roleService);
 }