Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.29 KB | None | 0 0
  1. protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
  2. {
  3. string userName = Login1.UserName;
  4. string password = Login1.Password;
  5. bool rememberUserName = Login1.RememberMeSet;
  6.  
  7. if (validateuser(userName, password))
  8. {
  9. //Fetch the role
  10. Database db = DatabaseFactory.CreateDatabase();
  11.  
  12.  
  13. //Create Command object
  14. System.Data.Common.DbCommand cmd = db.GetStoredProcCommand("sp_RolesForUser");
  15. db.AddInParameter(cmd, "@Uid", System.Data.DbType.String, 15);
  16. db.SetParameterValue(cmd, "@Uid", Login1.UserName);
  17. System.Data.IDataReader reader = db.ExecuteReader(cmd);
  18. System.Collections.ArrayList roleList = new System.Collections.ArrayList();
  19. if (reader.Read())
  20. {
  21. roleList.Add(reader[0]);
  22. string myRoles = (string)roleList[0];
  23.  
  24. //Create Form Authentication ticket
  25. //Parameter(1) = Ticket version
  26. //Parameter(2) = User ID
  27. //Parameter(3) = Ticket Current Date and Time
  28. //Parameter(4) = Ticket Expiry
  29. //Parameter(5) = Remember me check
  30. //Parameter(6) = User Associated Roles in this ticket
  31. //Parameter(7) = Cookie Path (if any)
  32. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now,
  33. DateTime.Now.AddMinutes(20), rememberUserName, myRoles, FormsAuthentication.FormsCookiePath);
  34.  
  35. //For security reasons we may hash the cookies
  36. string hashCookies = FormsAuthentication.Encrypt(ticket);
  37. HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
  38.  
  39. // add the cookie to user browser
  40. Response.Cookies.Add(cookie);
  41.  
  42. if (HttpContext.Current.User.IsInRole("Administrators"))
  43. {
  44. Response.Redirect("~/Admin/Default.aspx");
  45. }
  46. else
  47. {
  48. string returnURL = "~/Default.aspx";
  49.  
  50. // get the requested page
  51. //string returnUrl = Request.QueryString["ReturnUrl"];
  52. //if (returnUrl == null)
  53. // returnUrl = "~/Default.aspx";
  54. Response.Redirect(returnURL);
  55. }
  56. }
  57. }
  58. }
  59.  
  60. protected bool validateuser(string UserName, string Password)
  61. {
  62. Boolean boolReturnValue = false;
  63.  
  64. //Create Connection using Enterprise Library Database Factory
  65. Database db = DatabaseFactory.CreateDatabase();
  66.  
  67. //Create Command object
  68. DbCommand cmd = db.GetStoredProcCommand("sp_ValidateUser");
  69.  
  70. db.AddInParameter(cmd, "@userid", DbType.String, 15);
  71. db.SetParameterValue(cmd, "@userid", Login1.UserName);
  72.  
  73. db.AddInParameter(cmd, "@password", DbType.String, 15);
  74. db.SetParameterValue(cmd, "@password", Login1.Password);
  75.  
  76. db.AddOutParameter(cmd, "@retval", DbType.Int16, 2);
  77. db.ExecuteNonQuery(cmd);
  78.  
  79. int theStatus = (System.Int16)db.GetParameterValue(cmd, "@retval");
  80.  
  81. if (theStatus > 0) //Authenticated user
  82. boolReturnValue = true;
  83. else //UnAuthorized...
  84. boolReturnValue = false;
  85.  
  86. return boolReturnValue;
  87. }
  88.  
  89. public class User
  90. {
  91. public int UserId { get; set; }
  92. public string Name { get; set; }
  93. public string Username { get; set; }
  94. public string Password { get; set; }
  95. public string Email { get; set; }
  96. public bool IsAdmin { get; set; }
  97. }
  98.  
  99. public class UserRepository
  100. {
  101. Context context = new Context();
  102. public User GetByUsernameAndPassword(User user)
  103. {
  104. return context.Users.Where(u => u.Username==user.Username & u.Password==user.Password).FirstOrDefault();
  105. }
  106. }
  107.  
  108. public class UserApplication
  109. {
  110. UserRepository userRepo = new UserRepository();
  111. public User GetByUsernameAndPassword(User user)
  112. {
  113. return userRepo.GetByUsernameAndPassword(user);
  114. }
  115. }
  116.  
  117. public class AccountController : Controller
  118. {
  119. UserApplication userApp = new UserApplication();
  120. SessionContext context = new SessionContext();
  121.  
  122. public ActionResult Login()
  123. {
  124. return View();
  125. }
  126. [HttpPost]
  127. public ActionResult Login(User user)
  128. {
  129. var authenticatedUser = userApp.GetByUsernameAndPassword(user);
  130. if (authenticatedUser != null)
  131. {
  132. context.SetAuthenticationToken(authenticatedUser.UserId.ToString(),false, authenticatedUser);
  133. return RedirectToAction("Index", "Home");
  134. }
  135.  
  136. return View();
  137. }
  138.  
  139. public ActionResult Logout()
  140. {
  141. FormsAuthentication.SignOut();
  142. return RedirectToAction("Index", "Home");
  143. }
  144.  
  145. public class SessionContext
  146. {
  147. public void SetAuthenticationToken(string name, bool isPersistant, User userData)
  148. {
  149. string data = null;
  150. if (userData != null)
  151. data = new JavaScriptSerializer().Serialize(userData);
  152.  
  153. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, name, DateTime.Now, DateTime.Now.AddYears(1), isPersistant, userData.UserId.ToString());
  154.  
  155. string cookieData = FormsAuthentication.Encrypt(ticket);
  156. HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieData)
  157. {
  158. HttpOnly = true,
  159. Expires = ticket.Expiration
  160. };
  161.  
  162. HttpContext.Current.Response.Cookies.Add(cookie);
  163. }
  164.  
  165. public User GetUserData()
  166. {
  167. User userData = null;
  168.  
  169. try
  170. {
  171. HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
  172. if (cookie != null)
  173. {
  174. FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
  175.  
  176. userData = new JavaScriptSerializer().Deserialize(ticket.UserData, typeof(User)) as User;
  177. }
  178. }
  179. catch (Exception ex)
  180. {
  181. }
  182.  
  183. return userData;
  184. }
  185. }
  186.  
  187. <authentication mode="Forms">
  188. <forms loginUrl="~/Account/Login" timeout="2880" />
  189. </authentication>
  190.  
  191. [Authorize]
  192. public class ClassController : Controller
  193. {
  194. ...
  195. }
  196.  
  197. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement