PageRenderTime 45ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/sipsorcery-core/SIPSorcery.Web.Services/SIPSorceryAuthorisationService.cs

https://github.com/thecc4re/sipsorcery-mono
C# | 216 lines | 159 code | 20 blank | 37 comment | 24 complexity | d685d961a13cd29b428d0f17b4116a5a MD5 | raw file
Possible License(s): CC-BY-SA-3.0
  1. //-----------------------------------------------------------------------------
  2. // Filename: SIPSorceryAuthenticatedService.cs
  3. //
  4. // Description: This class servces as a base class for higher level services that
  5. // require authentication.
  6. //
  7. // History:
  8. // 22 Feb 2010 Aaron Clauson Created.
  9. //
  10. // License:
  11. // This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
  12. //
  13. // Copyright (c) 2010 Aaron Clauson (aaron@sipsorcery.com), SIPSorcery Ltd, London, UK
  14. // All rights reserved.
  15. //
  16. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that
  17. // the following conditions are met:
  18. //
  19. // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  20. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
  21. // disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Blue Face Ltd.
  22. // nor the names of its contributors may be used to endorse or promote products derived from this software without specific
  23. // prior written permission.
  24. //
  25. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
  26. // BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  27. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  28. // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  29. // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  30. // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  31. // POSSIBILITY OF SUCH DAMAGE.
  32. //-----------------------------------------------------------------------------
  33. using System;
  34. using System.Collections.Generic;
  35. using System.Linq;
  36. using System.ServiceModel;
  37. using System.ServiceModel.Activation;
  38. using System.ServiceModel.Description;
  39. using System.ServiceModel.Channels;
  40. using System.Text.RegularExpressions;
  41. using System.Web;
  42. using SIPSorcery.CRM;
  43. using SIPSorcery.Persistence;
  44. using SIPSorcery.SIP.App;
  45. using SIPSorcery.Sys;
  46. using SIPSorcery.Sys.Auth;
  47. using log4net;
  48. namespace SIPSorcery.Web.Services
  49. {
  50. public class SIPSorceryAuthorisationService
  51. {
  52. private ILog logger = AppState.logger;
  53. private static readonly string m_authIDKey = ServiceAuthToken.AUTH_TOKEN_KEY;
  54. protected CustomerSessionManager CRMSessionManager;
  55. protected SIPAssetPersistor<Customer> CRMCustomerPersistor;
  56. public SIPSorceryAuthorisationService()
  57. {
  58. SIPSorceryConfiguration sipSorceryConfig = new SIPSorceryConfiguration();
  59. CRMSessionManager = new CustomerSessionManager(sipSorceryConfig);
  60. CRMCustomerPersistor = CRMSessionManager.CustomerPersistor;
  61. }
  62. public SIPSorceryAuthorisationService(CustomerSessionManager crmSessionManager)
  63. {
  64. CRMSessionManager = crmSessionManager;
  65. CRMCustomerPersistor = crmSessionManager.CustomerPersistor;
  66. }
  67. protected bool IsServiceAlive()
  68. {
  69. logger.Debug("IsAlive called from " + OperationContext.Current.Channel.RemoteAddress + ".");
  70. return true;
  71. }
  72. public string Authenticate(string username, string password)
  73. {
  74. logger.Debug("SIPSorceryAuthenticatedService Authenticate called for " + username + ".");
  75. if (username == null || username.Trim().Length == 0)
  76. {
  77. return null;
  78. }
  79. else
  80. {
  81. string ipAddress = null;
  82. if (OperationContext.Current != null)
  83. {
  84. OperationContext context = OperationContext.Current;
  85. MessageProperties properties = context.IncomingMessageProperties;
  86. RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
  87. if (endpoint != null)
  88. {
  89. ipAddress = endpoint.Address;
  90. }
  91. }
  92. else if (HttpContext.Current != null)
  93. {
  94. ipAddress = HttpContext.Current.Request.UserHostAddress;
  95. }
  96. CustomerSession customerSession = CRMSessionManager.Authenticate(username, password, ipAddress);
  97. if (customerSession != null)
  98. {
  99. // If running in IIS add a cookie for javascript clients.
  100. if (HttpContext.Current != null)
  101. {
  102. logger.Debug("Setting authid cookie for " + customerSession.CustomerUsername + ".");
  103. HttpCookie authCookie = new HttpCookie(m_authIDKey, customerSession.SessionID);
  104. authCookie.Secure = HttpContext.Current.Request.IsSecureConnection;
  105. authCookie.HttpOnly = true;
  106. authCookie.Expires = DateTime.Now.AddMinutes(customerSession.TimeLimitMinutes);
  107. HttpContext.Current.Response.Cookies.Set(authCookie);
  108. }
  109. return customerSession.SessionID;
  110. }
  111. else
  112. {
  113. return null;
  114. }
  115. }
  116. }
  117. protected Customer AuthoriseRequest()
  118. {
  119. try
  120. {
  121. string authId = ServiceAuthToken.GetAuthId();
  122. //logger.Debug("Authorising request for sessionid=" + authId + ".");
  123. if (authId != null)
  124. {
  125. CustomerSession customerSession = CRMSessionManager.Authenticate(authId);
  126. if (customerSession == null)
  127. {
  128. logger.Warn("SIPSorceryAuthenticatedService AuthoriseRequest failed for " + authId + ".");
  129. throw new UnauthorizedAccessException();
  130. }
  131. else
  132. {
  133. Customer customer = CRMCustomerPersistor.Get(c => c.CustomerUsername == customerSession.CustomerUsername);
  134. return customer;
  135. }
  136. }
  137. else
  138. {
  139. logger.Warn("SIPSorceryAuthenticatedService AuthoriseRequest failed no authid header.");
  140. throw new UnauthorizedAccessException();
  141. }
  142. }
  143. catch (UnauthorizedAccessException)
  144. {
  145. throw;
  146. }
  147. catch (Exception excp)
  148. {
  149. logger.Error("Exception AuthoriseRequest. " + excp.Message);
  150. throw new Exception("There was an exception authorising the request.");
  151. }
  152. }
  153. protected void ExpireSession()
  154. {
  155. try
  156. {
  157. Customer customer = AuthoriseRequest();
  158. logger.Debug("SIPSorceryAuthenticatedService ExpireSession called for " + customer.CustomerUsername + ".");
  159. CRMSessionManager.ExpireToken(ServiceAuthToken.GetAuthId());
  160. // If running in IIS remove the cookie.
  161. if (HttpContext.Current != null)
  162. {
  163. HttpContext.Current.Request.Cookies.Remove(m_authIDKey);
  164. }
  165. }
  166. catch (UnauthorizedAccessException)
  167. {
  168. // This exception will occur if the SIP Server agent is restarted and the client sends a previously valid token.
  169. //logger.Debug("An unauthorised exception was thrown in logout.");
  170. }
  171. catch (Exception excp)
  172. {
  173. logger.Error("Exception ExpireSession. " + excp.Message);
  174. }
  175. }
  176. protected void ExtendExistingSession(int minutes)
  177. {
  178. try
  179. {
  180. Customer customer = AuthoriseRequest();
  181. logger.Debug("SIPSorceryAuthenticatedService ExtendExistingSession called for " + customer.CustomerUsername + " and " + minutes + " minutes.");
  182. if (HttpContext.Current != null)
  183. {
  184. HttpCookie authIdCookie = HttpContext.Current.Request.Cookies[m_authIDKey];
  185. authIdCookie.Expires = authIdCookie.Expires.AddMinutes(minutes);
  186. }
  187. CRMSessionManager.ExtendSession(ServiceAuthToken.GetAuthId(), minutes);
  188. }
  189. catch (Exception excp)
  190. {
  191. logger.Error("Exception ExtendExistingSession. " + excp.Message);
  192. throw;
  193. }
  194. }
  195. }
  196. }