public HttpCookie CreateFormsAuthenticationCookie(OpenIdUser user) { Random rand = new Random(); int randomInt = rand.Next(0, int.MaxValue); string hashValue = MD5Encryptor.GetHash(randomInt.ToString()); using (CookiesRepository cookiesRep = new CookiesRepository()) { Cooky existingCookie = cookiesRep.GetList().FirstOrDefault(x => x.UserId == user.UserId); if (existingCookie != null) { if (cookiesRep.Delete(existingCookie.Id) == false) { return(null); } } Cooky newCookie = new Cooky() { UserId = user.UserId, HashValue = hashValue }; if (cookiesRep.Create(newCookie) == false) { return(null); } } //var ticket = new FormsAuthenticationTicket(1, user.FullName, DateTime.Now, DateTime.Now.AddDays(7), true, user.GetCookieString(hashValue)); //var encrypted = FormsAuthentication.Encrypt(ticket).ToString(); var cookie = new HttpCookie(LOGIN_COOKIE_NAME, user.GetCookieString(hashValue)); return(cookie); }
public HttpCookie CreateFormsAuthenticationCookie(OpenIdUser user) { var ticket = new FormsAuthenticationTicket(1, user.Nickname, DateTime.Now, DateTime.Now.AddDays(7), true, user.ToString()); var encrypted = FormsAuthentication.Encrypt(ticket).ToString(); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); return(cookie); }
public async Task Handle(RegisterUserLogIn notification, CancellationToken cancellationToken) { var openIdUser = OpenIdUser.Create(notification.Claims); var result = await _userRepository.CreateAsync(User.Create(openIdUser)); _logger.LogDebug("[User] [Login] {user}", result); }
public OpenIdUser GetUser() { OpenIdUser user = null; IAuthenticationResponse openIdResponse = openId.GetResponse(); if (openIdResponse.IsSuccessful()) { user = ResponseIntoUser(openIdResponse); } return(user); }
public static void OrdersExported(OpenIdUser exporter, UrlHelper url, int itemsExported, byte[] exportedFile) { EmailMethods emailMethods = new EmailMethods(FROM_ADDRESS, Loc.Dic.OrdersSystem, FROM_PASSWORD); string emailSubject = String.Format("{0} {1}", itemsExported, Loc.Dic.Email_OrdersWereExported); StringBuilder emailBody = new StringBuilder(); emailBody.AppendLine(emailSubject); emailBody.AppendLine(); emailBody.AppendLine(Loc.Dic.Email_CopyOfExportedFileIsAttached); SendNotification(url, exporter.Email, exporter.FirstName, emailSubject, emailBody, exporter.NotificationEmail, exporter.NotificationCode, exportedFile, EXPORT_ORDERS_FILE_NAME); }
public static void OrderStatusChanged(Order order, OpenIdUser updater, UrlHelper url) { EmailMethods emailMethods = new EmailMethods(FROM_ADDRESS, Loc.Dic.OrdersSystem, FROM_PASSWORD); string emailSubject = String.Format("{0} {1} {2} {3} {4}", Loc.Dic.Order, order.OrderNumber, Translation.Status((StatusType)order.StatusId), Loc.Dic.By, updater.FullName); StringBuilder emailBody = new StringBuilder(); emailBody.AppendLine(emailSubject); emailBody.AppendLine(); emailBody.AppendLine(String.Format("{0}: {1}", Loc.Dic.SeeDetailsAt, url.Action("Details", "Orders", new { id = order.Id }, "http"))); SendNotification(url, order.User.Email, order.User.FirstName, emailSubject, emailBody, order.User.NotificationEmail, order.User.NotificationCode); }
public static User Create(OpenIdUser openIdUser) { var result = new User { Id = Guid.NewGuid(), AlternateId = openIdUser.Id, Email = openIdUser.EmailAddress, IsVerified = openIdUser.IsEmailVerified ? Status.Active : Status.Inactive, FirstName = string.Empty, MiddleName = string.Empty, LastName = string.Empty, BloodGroup = BloodGroup.None }; return(result); }
private OpenIdUser ResponseIntoUser(IAuthenticationResponse response) { OpenIdUser user = null; var claimResponseUntrusted = response.GetUntrustedExtension <FetchResponse>(); var claimResponse = response.GetExtension <FetchResponse>(); if (claimResponse != null) { user = new OpenIdUser(claimResponse, response.ClaimedIdentifier); } else if (claimResponseUntrusted != null) { user = new OpenIdUser(claimResponseUntrusted, response.ClaimedIdentifier); } return(user); }
protected void Page_Load(object sender, EventArgs e) { user = DataObject.Load <DataObjectUser>(UserProfile.Current.UserId, null, true); if (user.State != ObjectState.Added) { if (!string.IsNullOrEmpty(user.OpenID)) { this.LitOpenIDCur.Text = user.OpenID; } else { this.LitOpenIDCur.Text = language.GetString("MessageOpenIdNone"); } } if (!IsPostBack) { OpenIdClient openID = new OpenIdClient(); switch (openID.RequestedMode) { case RequestedMode.IdResolution: openID.Identity = UserProfile.Current.OpenID; if (openID.ValidateResponse()) { OpenIdUser openIDUser = openID.RetrieveUser(); user.OpenID = openIDUser.Identity; user.Update(UserDataContext.GetUserDataContext()); UserProfile.Current.OpenID = string.Empty; UserProfile.Current.Save(); this.LitOpenIDMsg.Text = language.GetString("MessageOpenIdConfirmed"); this.LitOpenIDCur.Text = user.OpenID; } else { this.LitOpenIDMsg.Text = language.GetString("MessageOpenIdNotConfirmed"); } break; case RequestedMode.CanceledByUser: this.LitOpenIDMsg.Text = language.GetString("MessageOpenIdCanceled"); break; } } }
public static Participant AttachParticipantProfileToOpenIdIdentity(int userId, string openIdUrl) { using (DaemonEntities entities = new DaemonEntities()) { OpenIdUser user = (from u in entities.OpenIdUser where u.UserId == userId select u).First <OpenIdUser>(); Participant participant = QueryUtil.First <Participant>(from p in entities.Participant where p.User.UserId == user.UserId select p); // If participant is not attached try to find existing participant with openIdUrl if (participant == null) { participant = QueryUtil.First <Participant>(from p in entities.Participant where p.OpenIdUrl == openIdUrl select p); if (participant != null) { // If participant is not attached to user then attach it. if (participant.User == null) { participant.User = user; entities.SaveChanges(); } else { throw new ArgumentException("Participant exists with the same OpenId but already connected to different user."); } } } // If participant is still null then create new participant and attach to user. if (participant == null) { participant = new Participant { ParticipantId = new Guid(UUIDGenerator.Current.GenerateNameBasedUUID(new UUID(MxpConstants.MxpNamespaceId.ToString()), openIdUrl).ToString()), OpenIdUrl = openIdUrl, User = user }; entities.AddToParticipant(participant); entities.SaveChanges(); } entities.Detach(participant); return(participant); } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { var isAuthorized = base.AuthorizeCore(httpContext); if (isAuthorized) { var authenticatedCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authenticatedCookie != null) { var authenticatedCookieValue = authenticatedCookie.Value.ToString(); if (!string.IsNullOrWhiteSpace(authenticatedCookieValue)) { var decryptedTicket = FormsAuthentication.Decrypt(authenticatedCookieValue); var user = new OpenIdUser(decryptedTicket.UserData); var openIdIdentity = new OpenIdIdentity(user); httpContext.User = new GenericPrincipal(openIdIdentity, null); } } } return(isAuthorized); }
private IEnumerable<ItemTransactionAnswer> PopulateItemTransactionAnswer(OpenIdUser openIdUser, ICollection<ItemQuestionSet> questionSets) { var answers = new List<ItemTransactionAnswer>(); // if anything is null, just return no answers if (openIdUser == null || questionSets == null) return answers; // find the contact information question set var questionSet = questionSets.Where(a => a.QuestionSet.Name == StaticValues.QuestionSet_ContactInformation).Select(a => a.QuestionSet).FirstOrDefault(); // if it exists, fill in the questions if (questionSet != null) { var questionAnswer = new Dictionary<string, string>(); questionAnswer.Add(StaticValues.Question_FirstName, openIdUser.FirstName); questionAnswer.Add(StaticValues.Question_LastName, openIdUser.LastName); questionAnswer.Add(StaticValues.Question_StreetAddress, openIdUser.StreetAddress); questionAnswer.Add(StaticValues.Question_AddressLine2, openIdUser.Address2); questionAnswer.Add(StaticValues.Question_City, openIdUser.City); questionAnswer.Add(StaticValues.Question_State, openIdUser.State); questionAnswer.Add(StaticValues.Question_Zip, openIdUser.Zip); questionAnswer.Add(StaticValues.Question_PhoneNumber, openIdUser.PhoneNumber); questionAnswer.Add(StaticValues.Question_Email, openIdUser.Email); foreach (var question in questionSet.Questions) { //If it doesn't find the question, it will throw an exception. (a good thing.) var ans = questionAnswer[question.Name]; // create the answer object var answer = new ItemTransactionAnswer() { Answer = ans, QuestionId = question.Id, QuestionSetId = question.QuestionSet.Id, Transaction = true }; answers.Add(answer); } #region old way answers were assigned //foreach(var question in questionSet.Questions) //{ // var ans = string.Empty; // if (question.Name == StaticValues.Question_FirstName) // { // ans = openIdUser.FirstName; // } // else if (question.Name == StaticValues.Question_LastName) // { // ans = openIdUser.LastName; // } // else if (question.Name == StaticValues.Question_StreetAddress) // { // ans = openIdUser.StreetAddress; // } // else if (question.Name == StaticValues.Question_AddressLine2) // { // ans = openIdUser.Address2; // } // else if (question.Name == StaticValues.Question_City) // { // ans = openIdUser.City; // } // else if (question.Name == StaticValues.Question_State) // { // ans = openIdUser.State; // } // else if (question.Name == StaticValues.Question_Zip) // { // ans = openIdUser.Zip; // } // else if (question.Name == StaticValues.Question_PhoneNumber) // { // ans = openIdUser.PhoneNumber; // } // else if (question.Name == StaticValues.Question_Email) // { // ans = openIdUser.Email; // } // // create the answer object // var answer = new ItemTransactionAnswer() // { // Answer = ans, // QuestionId = question.Id, // QuestionSetId = question.QuestionSet.Id, // Transaction = true // }; // answers.Add(answer); //} #endregion old way answers were assigned } return answers; }
public OpenIdIdentity(OpenIdUser user) { _user = user; }
/// <summary> /// Returns data for use by OpenIdUser object. /// </summary> /// <param name="userObject">The OpenIdUser object to populate.</param> public void PopulateUserObject(OpenIdUser userObject) { NameValueCollection Request = Parent.RequestArguments; foreach (string key in Request.Keys) { if (key != null && key.Contains("openid.pape.")) { if (Request[key] != null) { userObject.ExtensionData[key] = Request[key]; } } } }
private void HandleOpenIDLogin() { OpenIdClient openID = new OpenIdClient(); switch (openID.RequestedMode) { case RequestedMode.IdResolution: openID.Identity = UserProfile.Current.OpenID; if (openID.ValidateResponse()) { OpenIdUser openIDUser = openID.RetrieveUser(); UserProfile.Current.OpenID = string.Empty; UserProfile.Current.Save(); CSBooster_DataContext csb = new CSBooster_DataContext(Helper.GetSiemeConnectionString()); var user = csb.hisp_DataObject_GetUserIDByOpenID(openIDUser.Identity).ElementAtOrDefault(0); if (user != null) // User exists { MembershipUser membershipUser = Membership.GetUser(user.USR_ID); if (membershipUser != null) { PerformLogin(membershipUser.UserName); } } else // User doesn't exist { string nickname = openIDUser.GetValue("openid.sreg.nickname"); string email = openIDUser.GetValue("openid.sreg.email"); string fullname = openIDUser.GetValue("openid.sreg.fullname") ?? nickname; string gender = openIDUser.GetValue("openid.sreg.gender"); string firstname = string.Empty; string lastname = string.Empty; if (!string.IsNullOrEmpty(nickname) && !string.IsNullOrEmpty(email)) { string[] splitFullname = fullname.Split(' '); if (splitFullname.Length > 0) { firstname = splitFullname[0]; } if (splitFullname.Length > 1) { lastname = splitFullname[1]; } if (DataObjectUser.CreateUser(AuthenticationType.OpenID, openIDUser.Identity, nickname, email, firstname, lastname, gender)) { PerformLogin(nickname); } } else { LitOpenIDMsg.Text = language.GetString("MessageOpenIDNoDataReceived"); } } } else { LitOpenIDMsg.Text = language.GetString("MessageOpenIDLoginNotSuccess"); } break; case RequestedMode.CanceledByUser: LitOpenIDMsg.Text = language.GetString("MessageOpenIDLoginCancel"); break; } }
/// <summary> /// Gets the user object data needed to populate an <see cref="OpenIdUser"/> object. /// </summary> /// <remarks> /// Specifically sets the Identity and BaseIdentity properties of /// the OpenIdUser object. /// </remarks> /// <param name="userObject">The OpenIdUser object to populate.</param> public void PopulateUserObject(OpenIdUser userObject) { NameValueCollection arguments = Parent.RequestArguments; string identity = arguments["openid.identity"]; string claimed_id = null; string local_id = null; if (userObject.LastDiscoveryResult != null) { claimed_id = userObject.LastDiscoveryResult.ClaimedId; local_id = userObject.LastDiscoveryResult.LocalId; } userObject.BaseIdentity = identity; if (!String.IsNullOrEmpty(claimed_id)) { userObject.Identity = claimed_id; } if (claimed_id == local_id) { userObject.Identity = Utility.Normalize(identity, Parent.DiscoveryPlugIns).FriendlyId; } else { userObject.Identity = Utility.Normalize(claimed_id, Parent.DiscoveryPlugIns).FriendlyId; } }
/// <summary> /// Gets data for use by OpenIdUser object. /// </summary> /// <param name="userObject">The OpenIdUser object to populate.</param> public void PopulateUserObject(OpenIdUser userObject) { NameValueCollection Request = Parent.RequestArguments; AttributeExchangeItem[] aeis = DecodeUserData(Request); foreach (AttributeExchangeItem aei in aeis) { userObject.ExtensionData.Add(aei.IdUri.AbsoluteUri, String.Join(", ", aei.Values)); } }
/// <summary> /// Populate the OpenIDUser object. This method does nothing. /// </summary> /// <param name="userObject">The OpenIdUser object to populate.</param> public void PopulateUserObject(OpenIdUser userObject) { return; }
/// <summary> /// Gets the user object data needed to populate an <see cref="OpenIdUser"/> object. /// </summary> /// <remarks> /// Populates the OpenIdUser.ExtensionData property. /// </remarks> /// <param name="userObject">The OpenIdUser object to populate.</param> public void PopulateUserObject(OpenIdUser userObject) { NameValueCollection Request = Parent.RequestArguments; foreach (string key in Request.Keys) { if (key != null && key.StartsWith(_Prefix, StringComparison.OrdinalIgnoreCase)) { if (Request[key] != null) { userObject.ExtensionData[key] = Request[key]; } } } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if ( HttpContext.Current.Session["User"] == null ) { var authenticatedCookie = httpContext.Request.Cookies[OpenIdMembershipService.LOGIN_COOKIE_NAME]; if (authenticatedCookie != null) { var authenticatedCookieValue = authenticatedCookie.Value.ToString(); if (!string.IsNullOrWhiteSpace(authenticatedCookieValue)) { var user = OpenIdUser.FromCookieString(authenticatedCookieValue); if (user != null && user.IsActive) { HttpContext.Current.Session.Add("User", user); } else { HttpCookie myCookie = new HttpCookie(OpenIdMembershipService.LOGIN_COOKIE_NAME); myCookie.Expires = DateTime.Now.AddDays(-1d); httpContext.Response.Cookies.Add(myCookie); } } } } else { OpenIdUser sessionUser = (OpenIdUser)HttpContext.Current.Session["User"]; User databaseUser; using (AllUsersRepository allUserRep = new AllUsersRepository()) { databaseUser = allUserRep.GetEntity(sessionUser.UserId); } if (databaseUser != null) { sessionUser.Roles = databaseUser.Roles; } if (databaseUser == null || !databaseUser.IsActive) { HttpContext.Current.Session.Remove("User"); HttpCookie myCookie = new HttpCookie(OpenIdMembershipService.LOGIN_COOKIE_NAME); myCookie.Expires = DateTime.Now.AddDays(-1d); HttpContext.Current.Response.Cookies.Add(myCookie); } } if (HttpContext.Current.Session["User"] != null) { //Create culture info object CultureInfo ci = new CultureInfo(((OpenIdUser)HttpContext.Current.Session["User"]).LanguageCode); System.Threading.Thread.CurrentThread.CurrentUICulture = ci; System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name); } return(HttpContext.Current.Session["User"] != null); }
public HttpCookie CreateFormsAuthenticationCookie(OpenIdUser user) { Random rand = new Random(); int randomInt = rand.Next(0, int.MaxValue); string hashValue = MD5Encryptor.GetHash(randomInt.ToString()); using (CookiesRepository cookiesRep = new CookiesRepository()) { Cooky existingCookie = cookiesRep.GetList().FirstOrDefault(x => x.UserId == user.UserId); if (existingCookie != null) { if (cookiesRep.Delete(existingCookie.Id) == false) return null; } Cooky newCookie = new Cooky() { UserId = user.UserId, HashValue = hashValue }; if (cookiesRep.Create(newCookie) == false) return null; } //var ticket = new FormsAuthenticationTicket(1, user.FullName, DateTime.Now, DateTime.Now.AddDays(7), true, user.GetCookieString(hashValue)); //var encrypted = FormsAuthentication.Encrypt(ticket).ToString(); var cookie = new HttpCookie(LOGIN_COOKIE_NAME, user.GetCookieString(hashValue)); return cookie; }