Created
July 19, 2012 17:52
-
-
Save woloski/3145640 to your computer and use it in GitHub Desktop.
link account jabbr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void LinkAccount(IJabbrRepository repository, IChatService chatService, HttpContext context, string userIdentity, string username, string email) | |
{ | |
// Try to get the user by identity | |
ChatUser user = repository.GetUserByIdentity(userIdentity); | |
// No user with this identity | |
if (user == null) | |
{ | |
// See if the user is already logged in (via cookie) | |
var clientState = GetClientState(context); | |
user = repository.GetUserById(clientState.UserId); | |
if (user != null) | |
{ | |
// If they are logged in then assocate the identity | |
user.Identity = userIdentity; | |
user.Email = email; | |
if (!String.IsNullOrEmpty(email) && | |
String.IsNullOrEmpty(user.Hash)) | |
{ | |
user.Hash = email.ToMD5(); | |
} | |
repository.CommitChanges(); | |
} | |
else | |
{ | |
// There's no logged in user so create a new user with the associated credentials | |
// but first, let's clean up that username! | |
username = FixUserName(username); | |
user = chatService.AddUser(username, userIdentity, email); | |
SaveClientState(context, user); | |
} | |
} | |
else | |
{ | |
// Update email and gravatar | |
user.Email = email; | |
if (!String.IsNullOrEmpty(email) && | |
String.IsNullOrEmpty(user.Hash)) | |
{ | |
user.Hash = email.ToMD5(); | |
} | |
repository.CommitChanges(); | |
SaveClientState(context, user); | |
} | |
} | |
private static void SaveClientState(HttpContext context, ChatUser user) | |
{ | |
// Save the cokie state | |
var state = JsonConvert.SerializeObject(new { userId = user.Id }); | |
var cookie = new HttpCookie("jabbr.state", state); | |
cookie.Expires = DateTime.Now.AddDays(30); | |
context.Response.Cookies.Add(cookie); | |
} | |
private ClientState GetClientState(HttpContext context) | |
{ | |
// New client state | |
var jabbrState = GetCookieValue(context, "jabbr.state"); | |
ClientState clientState = null; | |
if (String.IsNullOrEmpty(jabbrState)) | |
{ | |
clientState = new ClientState(); | |
} | |
else | |
{ | |
clientState = JsonConvert.DeserializeObject<ClientState>(jabbrState); | |
} | |
return clientState; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment