Skip to content

Instantly share code, notes, and snippets.

@ArnisL
Created October 19, 2010 13:27
Show Gist options
  • Save ArnisL/634186 to your computer and use it in GitHub Desktop.
Save ArnisL/634186 to your computer and use it in GitHub Desktop.
userSession.cs
public class UserSession:IUserSession{
private readonly IAuthenticationService _authenticationService;
private readonly ICryptographer _crypto;
private readonly IUserRepository _repository;
public UserSession(IUserRepository repository,IAuthenticationService authenticationService,ICryptographer crypto){
Guard.AgainstNull(repository);
Guard.AgainstNull(authenticationService);
Guard.AgainstNull(crypto);
_repository=repository;
_crypto=crypto;
_authenticationService=authenticationService;
}
public User GetCurrentUser(){
if(HttpContext.Current.User==null) return null;
var identity=HttpContext.Current.User.Identity;
if(!identity.IsAuthenticated) return null;
var user=_repository.ByUserName(identity.Name);
if(user==null) throw new Exception("User not found. It should be. Looks bad.");
return user;
}
public void LogIn(string userName,string password){
if(!_repository.ExistsWithUserName(userName)) Kaboom();
var user=_repository.ByUserName(userName);
if(!_authenticationService.PasswordMatches(user,password)) Kaboom();
LogIn(userName);
}
public void LogIn(string userName){
if(!_repository.ExistsWithUserName(userName)) Kaboom();
var user=_repository.ByUserName(userName);
var roles=user.Roles.Select(x=>x.Name.ToLower()).ToArray();
var ticket=new FormsAuthenticationTicket(1,user.UserName,DateTime.Now,DateTime.Now.AddMinutes(20),false,
string.Join(",",roles));
var encryptedTicket=FormsAuthentication.Encrypt(ticket);
var authCookie=new HttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket);
HttpContext.Current.Response.Cookies.Add(authCookie);
HttpContext.Current.User=new GenericPrincipal(new GenericIdentity(user.UserName),roles);
}
public void RegisterPassword(User user,string password){
if(user==null) throw new ApplicationException("User not found.");
var salt=_crypto.CreateSalt();
var hash=_crypto.GetPasswordHash(password,salt);
user.RegisterPassword(hash,salt);
LogIn(user.UserName,password);
}
public void LogOut(){
HttpContext.Current.User=null;
FormsAuthentication.SignOut();
}
private void Kaboom(){
throw new ApplicationException("User name or password is invalid.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment