Esempio n. 1
0
        /// <summary>
        /// Retrieves the auth user.
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        public static AuthUserData RetrieveAuthUser()
        {
            string     cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = HttpContext.Current.Request.Cookies(cookieName);
            FormsAuthenticationTicket authTicket = default(FormsAuthenticationTicket);
            string       userdata = string.Empty;
            AuthUserData aum      = new AuthUserData();         //AuthUserData is a custom serializable Poco that holds all the required user data for my cookie (userID, email address, whatever.

            if ((authCookie != null))
            {
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                userdata   = authTicket.UserData;
            }

            if ((!object.ReferenceEquals(userdata, string.Empty)))
            {
                aum = DeserializeUser(userdata);
                if (string.IsNullOrEmpty(aum.Username))
                {
                    aum.Username = "******" + aum.ID;
                }
            }
            else
            {
                aum.ID         = null;
                aum.Region     = null;
                aum.Username   = string.Empty;
                aum.Reputation = 0;
            }

            return(aum);
        }
Esempio n. 2
0
        public AuthUserData GetAuthInfoByName(string username)
        {
            var rolequery = (from users in _context.AppUser
                             join roles in _context.AppUserInRole on users.AppUserID equals roles.AppUserID
                             join roletypes in _context.RoleType on roles.RoleTypeID equals roletypes.RoleTypeID
                             join hrmap in _context.HREditorialUserMap on users.AppUserID equals hrmap.AppUserID
                             where hrmap.HumanReviewUserID == username
                             select new { roletypes.RoleTypeID, users.AppUserName, users.AppUserID, users.Email });

            AuthUserData userData  = null;
            var          querydata = rolequery.FirstOrDefault();

            if (querydata != null)
            {
                userData = new AuthUserData
                {
                    RoleTypeID = querydata.RoleTypeID,
                    UserName   = querydata.AppUserName,
                    AppUserId  = querydata.AppUserID.ToString(),
                    Email      = querydata.Email
                };
            }

            return(userData);
        }
Esempio n. 3
0
 /// <summary>
 /// Serializes the user.
 /// </summary>
 /// <param name="aum">The AuthUserData.</param>
 /// <returns></returns>
 /// <remarks>The AuthUserData is a custom serializable poco that holds the data</remarks>
 private static string SerializeUser(AuthUserData aud)
 {
     Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     IO.MemoryStream mem = new IO.MemoryStream();
     bf.Serialize(mem, aud);
     return(Convert.ToBase64String(mem.ToArray()));
 }
Esempio n. 4
0
        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            var cookies = Context.Request.Cookies;
            var session = Context.Session;

            Principal principal = null;

            if (cookies[CookieHelper.AuthCookieName] != null)
            {
                var authCookieData = cookies[CookieHelper.AuthCookieName].Value;

                if (authCookieData != null)
                {
                    try
                    {
                        var authCookieTicket = FormsAuthentication.Decrypt(authCookieData);

                        if (!authCookieTicket.Expired)
                        {
                            var authUserData = new AuthUserData();

                            if (authUserData.Import(authCookieTicket.UserData))
                            {
                                var isAuthenticated = false;

                                if (session.IsNewSession || session.SessionID != authUserData.SessionId)
                                {
                                    isAuthenticated = false;
                                }
                                else
                                {
                                    isAuthenticated = true;
                                }

                                principal = new Principal(authUserData.UserId.ToString(), isAuthenticated)
                                {
                                    UserId = authUserData.UserId
                                };
                            }
                        }
                    }
                    catch (Exception exception)
                    {

                    }
                }
            }

            Context.User = principal;
        }
Esempio n. 5
0
        public static HttpCookie CreateAuthCookie(string loginIdentifier, string sessionId, long userId)
        {
            var authUserData = new AuthUserData(sessionId, userId);
            var formsAuthTicket = new FormsAuthenticationTicket(
                1,
                loginIdentifier,
                DateTime.Now,
                DateTime.Now.AddDays(7),
                true,
                authUserData.Export());

            var authTicketEncryptedData = FormsAuthentication.Encrypt(formsAuthTicket);
            var httpCookie = new HttpCookie(AuthCookieName, authTicketEncryptedData);
            return httpCookie;
        }
        public async Task <ActionResult <AuthenticateResponse> > Login([FromBody] AuthUserData authUser)
        {
            var authResponse = await authenticationService.IsSignInSuccessful(authUser);

            switch (authResponse.Message)
            {
            case AuthResponseMessage.LoginAndPasswordNotProvided:
            case AuthResponseMessage.LoginNotProvided:
            case AuthResponseMessage.PasswordNotProvided:     // note that not providing password does not count as login attempt
            default:
                return(BadRequest(authResponse));

            case AuthResponseMessage.UserWithThisLoginNotExists:
                return(Conflict(authResponse.Message));

            case AuthResponseMessage.WrongPassword:
            {
                int userId = await userService.GetUserIdByLogin(authUser.Login);

                bool shouldBeBlocked = await loginHistoryService.CheckIfLogInShouldBeBlocked(userId);

                if (shouldBeBlocked)
                {
                    return(Conflict("Too many bad attempts. Try later."));
                }

                await loginHistoryService.AddLoginHistory(userId, false);

                return(Conflict(authResponse.Message));
            }

            case AuthResponseMessage.LoggedSucessfuly:
            {
                int userId = await userService.GetUserIdByLogin(authUser.Login);

                bool shouldBeBlocked = await loginHistoryService.CheckIfLogInShouldBeBlocked(userId);

                if (shouldBeBlocked)
                {
                    return(Conflict("Too many bad attempts. Try later."));
                }

                await loginHistoryService.AddLoginHistory(userId, true);

                return(Ok(authResponse));
            }
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Generate an Authentication Cookie that also contains "UserData".
        /// The UserData is a serialized "AuthUserData" Object containing "ID"
        /// "RegionID" "Username" and "Slug"
        /// </summary>
        /// <param name="userName">this is the "claimedidentifier" of the user's OpenId</param>
        /// <param name="userData">be mindful of the cookie size or you will be chasing ghosts</param>
        /// <param name="persistent"></param>
        public static HttpCookie CreateAuthCookie(string userName, AuthUserData userData, bool persistent)
        {
            DateTime issued = DateTime.UtcNow;
            // formsAuth does not expose timeout!? have to get around the spoiled
            // parts and keep moving..
            HttpCookie fooCookie    = FormsAuthentication.GetAuthCookie("foo", true);
            int        formsTimeout = Convert.ToInt32((fooCookie.Expires - DateTime.UtcNow).TotalMinutes);

            DateTime expiration = DateTime.UtcNow.AddMinutes(formsTimeout);
            string   cookiePath = FormsAuthentication.FormsCookiePath;

            string SerializedUser = SerializeUser(userData);

            object ticket = new FormsAuthenticationTicket(0, userName, issued, expiration, true, SerializedUser, cookiePath);

            return(CreateAuthCookie(ticket, expiration, persistent));
        }
Esempio n. 8
0
        public static AuthUserData AuthCookieData()
        {
            AuthUserData authUserData = null;

            if (Cookies[AuthCookieName] != null)
            {
                var authHttpCookie = Cookies[AuthCookieName].Value;
                var formsAuthTicket = FormsAuthentication.Decrypt(authHttpCookie);

                if (formsAuthTicket != null)
                {
                    authUserData = new AuthUserData();
                    authUserData.Import(formsAuthTicket.UserData);
                }
            }

            return authUserData;
        }
Esempio n. 9
0
        /// <summary>
        /// Method indicates whether sign in process was successful
        /// </summary>
        /// <param name="authUser"></param>
        /// <returns></returns>
        public async Task <AuthenticateResponse> IsSignInSuccessful(AuthUserData authUser)
        {
            bool isLoginNullOrEmpty    = string.IsNullOrEmpty(authUser.Login);
            bool isPasswordNullOrEmpty = string.IsNullOrEmpty(authUser.Password);

            if (isLoginNullOrEmpty && isPasswordNullOrEmpty)
            {
                return(new AuthenticateResponse(AuthResponseMessage.LoginAndPasswordNotProvided, null, null, null, null, null));
            }

            else if (isLoginNullOrEmpty)
            {
                return(new AuthenticateResponse(AuthResponseMessage.LoginNotProvided, null, null, null, null, null));
            }

            else if (isPasswordNullOrEmpty)
            {
                return(new AuthenticateResponse(AuthResponseMessage.PasswordNotProvided, null, null, null, null, null));
            }

            var userWithAuthLogin = await unitOfWork.UserRepository.GetUserByLoginAsync(authUser.Login);

            if (userWithAuthLogin == null)
            {
                return(new AuthenticateResponse(AuthResponseMessage.UserWithThisLoginNotExists, null, null, null, null, null));
            }

            HashPassword hash = new HashPassword(authUser.Password, authUser.Login);

            if (userWithAuthLogin.Password.Equals(hash.HashedPassword))
            {
                var userRole = await unitOfWork.UserRoleRepository.GetUserRole(userWithAuthLogin);

                var authResponseData = Authenticate(userWithAuthLogin, userRole);

                if (authResponseData == null)
                {
                    return(new AuthenticateResponse(AuthResponseMessage.ErrorWhileGeneratingToken, null, null, null, null, null));
                }

                return(authResponseData);
            }
            return(new AuthenticateResponse(AuthResponseMessage.WrongPassword, null, null, null, null, null));
        }
Esempio n. 10
0
        public bool Register(User user, string password, Role role)
        {
            if (_userDao.GetAll().Any(item => item.Name == user.Name))
            {
                return(false);
            }

            var userId = _userDao.Add(user);

            var authUserData = new AuthUserData {
                Password = password, UserId = userId
            };
            var authUserDataId = _authUserDataDao.Add(authUserData);

            user.AuthUserDataId = authUserDataId;
            _userDao.Update(user);

            _rolesManager.AddRoleToUser(user.Id, role.Id);

            return(true);
        }
Esempio n. 11
0
        public IActionResult GetMessageTest(AuthUserData authUserData)
        {
            HashPassword hashed = new HashPassword(authUserData.Password, authUserData.Login);

            return(Ok(hashed.HashedPassword));
        }