summaryrefslogtreecommitdiffstats
path: root/samples/OAuthServiceProvider/App_Code/Global.cs
blob: d32d9a72e21b69ecd7d90e754a157d8269e0f7e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
using System;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Web;
using DotNetOpenAuth.OAuth.Messages;

/// <summary>
/// The web application global events and properties.
/// </summary>
public class Global : HttpApplication {
	/// <summary>
	/// An application memory cache of recent log messages.
	/// </summary>
	public static StringBuilder LogMessages = new StringBuilder();

	/// <summary>
	/// The logger for this sample to use.
	/// </summary>
	public static log4net.ILog Logger = log4net.LogManager.GetLogger("DotNetOpenAuth.ConsumerSample");

	/// <summary>
	/// Gets the transaction-protected database connection for the current request.
	/// </summary>
	public static DataClassesDataContext DataContext {
		get {
			DataClassesDataContext dataContext = dataContextSimple;
			if (dataContext == null) {
				dataContext = new DataClassesDataContext();
				dataContext.Connection.Open();
				dataContext.Transaction = dataContext.Connection.BeginTransaction();
				dataContextSimple = dataContext;
			}

			return dataContext;
		}
	}

	public static DatabaseTokenManager TokenManager { get; set; }

	public static User LoggedInUser {
		get { return Global.DataContext.Users.SingleOrDefault(user => user.OpenIDClaimedIdentifier == HttpContext.Current.User.Identity.Name); }
	}

	public static UserAuthorizationRequest PendingOAuthAuthorization {
		get { return HttpContext.Current.Session["authrequest"] as UserAuthorizationRequest; }
		set { HttpContext.Current.Session["authrequest"] = value; }
	}

	private static DataClassesDataContext dataContextSimple {
		get {
			if (HttpContext.Current != null) {
				return HttpContext.Current.Items["DataContext"] as DataClassesDataContext;
			} else if (OperationContext.Current != null) {
				object data;
				if (OperationContext.Current.IncomingMessageProperties.TryGetValue("DataContext", out data)) {
					return data as DataClassesDataContext;
				} else {
					return null;
				}
			} else {
				throw new InvalidOperationException();
			}
		}

		set {
			if (HttpContext.Current != null) {
				HttpContext.Current.Items["DataContext"] = value;
			} else if (OperationContext.Current != null) {
				OperationContext.Current.IncomingMessageProperties["DataContext"] = value;
			} else {
				throw new InvalidOperationException();
			}
		}
	}

	public static void AuthorizePendingRequestToken() {
		ITokenContainingMessage tokenMessage = PendingOAuthAuthorization;
		TokenManager.AuthorizeRequestToken(tokenMessage.Token, LoggedInUser);
		PendingOAuthAuthorization = null;
	}

	private static void CommitAndCloseDatabaseIfNecessary() {
		var dataContext = dataContextSimple;
		if (dataContext != null) {
			dataContext.SubmitChanges();
			dataContext.Transaction.Commit();
			dataContext.Connection.Close();
		}
	}

	private void Application_Start(object sender, EventArgs e) {
		log4net.Config.XmlConfigurator.Configure();
		Logger.Info("Sample starting...");
		string appPath = HttpContext.Current.Request.ApplicationPath;
		if (!appPath.EndsWith("/")) {
			appPath += "/";
		}
		// This will break in IIS Integrated Pipeline mode, since applications
		// start before the first incoming request context is available.
		// TODO: fix this.
		Constants.WebRootUrl = new Uri(HttpContext.Current.Request.Url, appPath);
		var tokenManager = new DatabaseTokenManager();
		Global.TokenManager = tokenManager;
	}

	private void Application_End(object sender, EventArgs e) {
		Logger.Info("Sample shutting down...");

		// this would be automatic, but in partial trust scenarios it is not.
		log4net.LogManager.Shutdown();
	}

	private void Application_Error(object sender, EventArgs e) {
		Logger.Error("An unhandled exception occurred in ASP.NET processing: " + Server.GetLastError(), Server.GetLastError());
	}

	private void Application_EndRequest(object sender, EventArgs e) {
		CommitAndCloseDatabaseIfNecessary();
	}
}