using Newtonsoft.Json;
using System;
using System.Web;
using System.Web.Security;
using CommonFunc;

public class Userlogin
{
    /*Authorize a user after login.
     Use class name in Place of T and class object*/
    
    public static void AuthoriseUser<T>(T ClassName, string Email, bool RememberMe=false, string ReturnUrl="",string CookieName="")
    {
        string userData = JsonConvert.SerializeObject(ClassName);
        int ExpirationInMinute = (RememberMe == true) ? 5000 : 60;
        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket
            (
            1, Email, DateTime.Now, DateTime.Now.AddMinutes(ExpirationInMinute), false, userData
            );
        string enTicket = FormsAuthentication.Encrypt(authTicket);
        string cookie = (CookieName != "") ? CookieName : FormsAuthentication.FormsCookieName;
        var authCookie = new HttpCookie(cookie, enTicket);
        HttpContext.Current.Response.Cookies.Add(authCookie);
        if (ReturnUrl != "")
        {
            if (CheckFunc.IsLocalUrl(ReturnUrl) && ReturnUrl.Length > 1 && ReturnUrl.StartsWith("/")
                                && !ReturnUrl.StartsWith("//") && !ReturnUrl.StartsWith("/\\"))
            {
                HttpContext.Current.Response.Redirect(ReturnUrl);
            }
        }
    }
    /*Get Autorized User detail*/
    public static T getloginUserDetail<T>(T UserClass, string CookieName="")
    {
        string cookies = (CookieName != "") ? CookieName : FormsAuthentication.FormsCookieName;
        var authCookie = HttpContext.Current.Request.Cookies[cookies];
        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            if (authTicket != null && !authTicket.Expired)
            {
                UserClass = JsonConvert.DeserializeObject<T>(authTicket.UserData);
            }
        }
        return UserClass;
    }
}

