6 /// <summary>
7 /// this page will be used as a basePage class for all pages that needs to be secured .
8 /// so if you want to make some pages secured ,
9 /// just let them inherit from this class instead of directly inheriting from System.Web.UI.Page
10 /// </summary>
11 ///
12 public class SecuredPage : System.Web.UI.Page
13 {
14
15 protected string LoginUrl
16 {
17 get { return "~/Login.aspx"; }
18 }
19
20 // return true if the current page is the Login Page .
21 private bool IsLoginPage
22 {
23 get {
24 return VirtualPathUtility.GetFileName(Request.Path).ToLower() ==
25 VirtualPathUtility.GetFileName(LoginUrl.ToLower());
26 }
27 }
28
29 // Property to get/set the UserName from/in the session
30 private const string UserNameKey = "UserName";
31 protected string UserName
32 {
33 get
34 {
35 return Convert.ToString(Session[UserNameKey]);
36 }
37 set {
38 Session[UserNameKey] = value;
39 }
40 }
41
42 protected string DefaultPage
43 {
44 get {
45 return "Default.aspx";
46 }
47 }
48 protected void RequestLogin()
49 {
50 string CurrentUrl = Request.RawUrl;
51 Response.Redirect(LoginUrl + "?ReturnUrl=" + Server.HtmlEncode( CurrentUrl));
52 }
53
54 // use this method to redirect the user after sucessfull login ,
55 // this method will make sure that the user will get redirected to the original url that was on .
56
57 protected void RedirectFromLoginPage(string TargetUrl)
58 {
59 if (! string.IsNullOrEmpty(UserName))
60 {
61 if (Request.QueryString["ReturnUrl"] != null)
62 {
63 Response.Redirect(Request.QueryString["ReturnUrl"]);
64 }
65 else
66 Response.Redirect(TargetUrl);
67 }
68 }
69
70 // you can just call this method , it will automatically redirect to default page ,
71 protected void RedirectFromLoginPage()
72 {
73 RedirectFromLoginPage(DefaultPage);
74 }
75
76 protected override void OnInit(EventArgs e)
77 {
78 // if the user is not logged in , redirect to Login Page
79 if (string.IsNullOrEmpty(UserName) && !IsLoginPage)
80 RequestLogin();
81 // this needed to initialize its base page class
82 base.OnInit(e);
83 }
84 }