Ejemplo n.º 1
0
 public bool AddCredential(string credentialType, string accessToken, DateTime? expires, string renewalToken = null)
 {
     bool exists = false;
     UserCredential credential;
     // TODO: encrypt token
     if (this.UserCredentials.Any(uc => uc.CredentialType == credentialType))
     {   // update existing token
         credential = this.UserCredentials.Single<UserCredential>(uc => uc.CredentialType == credentialType);
         exists = true;
     }
     else
     {   // add new token
         credential = new UserCredential()
         {
             UserID = this.ID,
             CredentialType = credentialType,
         };
         this.UserCredentials.Add(credential);
     }
     credential.AccessToken = accessToken;
     credential.AccessTokenExpiration = expires;
     if (renewalToken != null) { credential.RenewalToken = renewalToken; }
     credential.LastModified = DateTime.UtcNow;
     return exists;
 }
Ejemplo n.º 2
0
 static bool IsValidPassword(UserCredential credentials, string password)
 {
     // hash of given password should match stored hash
     string hash = HashPassword(password, credentials.RenewalToken);
     return credentials.AccessToken.Equals(hash, StringComparison.Ordinal);
 }
Ejemplo n.º 3
0
        UserCredential RenewAccessToken(UserCredential googleConsent)
        {
            string format = "client_id={0}&client_secret={1}&refresh_token={2}&grant_type=refresh_token";
            string formParams = string.Format(format,
                    System.Web.HttpContext.Current.Server.UrlEncode(GoogleClient.ID),
                    System.Web.HttpContext.Current.Server.UrlEncode(GoogleClient.Secret),
                    System.Web.HttpContext.Current.Server.UrlEncode(googleConsent.RenewalToken));

            byte[] byteArray = Encoding.ASCII.GetBytes(formParams);
            const string googleOAuth2TokenServiceUrl = "https://accounts.google.com/o/oauth2/token";
            WebRequest request = WebRequest.Create(googleOAuth2TokenServiceUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;

            Stream outStream = request.GetRequestStream();
            outStream.Write(byteArray, 0, byteArray.Length);
            outStream.Close();
            try
            {
                WebResponse response = request.GetResponse();
                HttpStatusCode responseStatus = ((HttpWebResponse)response).StatusCode;
                Stream inStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(inStream);
                string jsonToken = reader.ReadToEnd();
                JsonGoogleToken token = JsonSerializer.Deserialize<JsonGoogleToken>(jsonToken);

                googleConsent.AccessToken = token.access_token;
                googleConsent.AccessTokenExpiration = DateTime.UtcNow.AddSeconds(token.expires_in);
                storage.SaveChanges();

                reader.Close();
                inStream.Close();
                response.Close();
            }
            catch (Exception e)
            {
                TraceLog.TraceException("Could not refresh Google access token", e);
            }
            return googleConsent;
        }
Ejemplo n.º 4
0
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            status = MembershipCreateStatus.Success;
            UserStorageContext storage = Storage.NewUserContext;

            const string emailPattern = "^[a-z0-9_\\+-]+([\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$";
            if (!Regex.IsMatch(email.ToLower(), emailPattern))
            {   // not valid email address
                status = MembershipCreateStatus.InvalidEmail;
                TraceLog.TraceInfo("Failed to create user account due to invalid email: " + email);
                return null;
            }

            if (password.Length < MinRequiredPasswordLength)
            {   // not a valid password
                status = MembershipCreateStatus.InvalidPassword;
                TraceLog.TraceInfo("Failed to create user account due to invalid password: "******"Failed to create duplicate user account: " + username);
                return null;
            }

            // create salt for each user and store hash of password
            string salt = CreateSalt(64);
            password = HashPassword(password, salt);
            Guid userID = (providerUserKey != null && providerUserKey is Guid) ? (Guid)providerUserKey : Guid.NewGuid();

            User user = new User()
            {
                ID = userID,
                Name = username.ToLower(),
                Email = email.ToLower(),
                CreateDate = DateTime.UtcNow
            };
            UserCredential credentials = new UserCredential()
            {
                UserID = user.ID,
                CredentialType = UserCredential.Password,
                AccessToken = password,
                RenewalToken = salt,
                LastModified = user.CreateDate
            };
            user.UserCredentials = new List<UserCredential>() { credentials };
            storage.Users.Add(user);
            storage.SaveChanges();
            user = storage.Users.Single<User>(u => u.Name == username);
            status = MembershipCreateStatus.Success;

            // Log creation of new user account
            TraceLog.TraceInfo("Created new user account: " + username);

            return AsMembershipUser(user);
        }