using GreenTree.Nachtragsmanagement.Core.Domain.User; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace GreenTree.Nachtragsmanagement.Core.Authentication { public class UserHelper : IUserHelper { /// /// Evaluates the current user from request cookies /// public User FromCookies() { return FromCookies(2); } /// /// Evaluates the current user from request cookies /// /// The hours the authCookie will be increased if it exists. public User FromCookies(int expirationHoursIncrease) { if (HttpContext.Current == null || HttpContext.Current.Session == null) return null; var authCookie = HttpContext.Current.Request.Cookies["auth"]; if (authCookie == null) return null; var user = JsonConvert.DeserializeObject(StaticHelper.DecompressString(authCookie.Value)); if (user != null) { authCookie.Expires = DateTime.Now.AddHours(expirationHoursIncrease); HttpContext.Current.Response.Cookies.Set(authCookie); } return user; } /// /// Writes the current user to response cookies /// /// The current authenticated user. public void ToCookies(User user) { if (HttpContext.Current == null || HttpContext.Current.Session == null) return; var authCookie = HttpContext.Current.Request.Cookies["auth"]; var userJson = JsonConvert.SerializeObject(user); authCookie = new HttpCookie("auth", StaticHelper.CompressString(userJson)) { Expires = authCookie.Expires }; HttpContext.Current.Response.Cookies.Set(authCookie); } /// /// Writes the current user to response cookies /// /// The current authenticated user. /// The cookie expiration date. public void ToCookies(User user, DateTime expirationDate) { if (HttpContext.Current == null || HttpContext.Current.Session == null) return; var authCookie = HttpContext.Current.Request.Cookies["auth"]; var userJson = JsonConvert.SerializeObject(user); authCookie = new HttpCookie("auth", StaticHelper.CompressString(userJson)) { Expires = expirationDate }; HttpContext.Current.Response.Cookies.Set(authCookie); } /// /// Clears the authentication cookie /// public void ClearCookie() { if (HttpContext.Current == null || HttpContext.Current.Session == null) return; var authCookie = HttpContext.Current.Request.Cookies["auth"]; authCookie.Expires = DateTime.Now.AddHours(-1); HttpContext.Current.Response.Cookies.Set(authCookie); } } }