Last active
August 29, 2015 14:17
-
-
Save stefan2410/00bba6f0344c36439746 to your computer and use it in GitHub Desktop.
TestSession
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Funq; | |
using ServiceStack; | |
using ServiceStack.Auth; | |
using ServiceStack.Configuration; | |
using grm.service.model; | |
using grm.service.auth; | |
namespace grm.service.model | |
{ | |
[Route("/API.GRM.Auth/APIAuthenticate", "POST", Summary = "GRM Service Authentication")] | |
public class APIAuthenticate | |
{ public string UserName { get; set; } | |
public string Password { get; set; } | |
public bool RememberMe { get; set; } | |
public string AppId { get; set; } } | |
public class APIAuthenticateResponse | |
{ | |
public bool Success { get; set; } | |
public string Message { get; set; } | |
public string ErrorCode { get; set; } | |
public int GrmUserId { get; set; } | |
public string UserName { get; set; } | |
public string SessionId { get; set; } | |
public string ReferrerUrl { get; set; } | |
public string GrmDisplayName { get; set; } | |
public string GrmUserRole { get; set; } | |
public string GrmCompany { get; set; } | |
public bool IsGrmActive { get; set; } | |
} | |
} | |
namespace grm.service.auth | |
{ | |
public class APIAuthServices : Service | |
{ | |
public APIAuthenticateResponse Post(APIAuthenticate request) | |
{ | |
using (var auth = base.ResolveService<AuthenticateService>()) | |
{ | |
var provider_request = new Authenticate | |
{ | |
provider = "APIAuthCredentials", | |
UserName = request.UserName, | |
Password = request.Password, | |
RememberMe = request.RememberMe, | |
}; | |
AuthenticateResponse authResponse = null; | |
try | |
{ | |
var response = auth.Post(provider_request); | |
authResponse = response as AuthenticateResponse; | |
object p = response.GetResponseDto(); | |
} | |
catch (HttpError err) | |
{ | |
return new APIAuthenticateResponse() { Success = false, Message = err.Message, ErrorCode = err.StatusCode.ToString() }; | |
} | |
catch (Exception err) | |
{ | |
return new APIAuthenticateResponse() { Success = false, Message = err.Message }; | |
} | |
finally { } | |
if (authResponse == null) | |
return new APIAuthenticateResponse() { Success = false, Message = "error" }; | |
var session = base.SessionAs<APIAuthUserSession>(); | |
if (!session.IsAuthenticated) | |
return new APIAuthenticateResponse() { Success = false, Message = "User not Authenticated" }; | |
session.AppId = request.AppId; | |
return new APIAuthenticateResponse() | |
{ | |
UserName = authResponse.UserName, | |
SessionId = authResponse.SessionId, | |
ReferrerUrl = authResponse.ReferrerUrl, | |
GrmUserId = session.GrmUserId, | |
GrmUserRole = session.GrmUserRole, | |
GrmCompany = session.GrmCompany, | |
IsGrmActive = session.IsGrmActive, | |
Success = true | |
}; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Funq; | |
using ServiceStack; | |
using ServiceStack.Auth; | |
namespace grm.service.auth | |
{ | |
public class APIAuthUserSession : AuthUserSession | |
{ | |
public int GrmUserId { get; set; } | |
public string GrmUserRole { get; set; } | |
public string GrmCompany { get; set; } | |
public bool IsGrmActive { get; set; } | |
public string AppId { get; set; } | |
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, System.Collections.Generic.Dictionary<string, string> authInfo) | |
{ | |
base.OnAuthenticated(authService, session, tokens, authInfo); | |
if (session.UserName == "grmadmin") | |
{ | |
APIAuthUserSession apisession = session as APIAuthUserSession; | |
if (apisession != null) | |
{ | |
apisession.GrmUserId = 111; | |
apisession.GrmCompany = "Carpark"; | |
apisession.IsGrmActive = true; | |
apisession.GrmUserRole = "OPERATOR"; | |
} | |
} | |
} | |
public override void OnLogout(IServiceBase authService) | |
{ | |
base.OnLogout(authService); | |
} | |
} | |
public class APICredentialsAuthProvider : CredentialsAuthProvider | |
{ | |
public APICredentialsAuthProvider() | |
: base() | |
{ | |
this.Provider = "APIAuthCredentials"; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Data.SqlClient; | |
using Funq; | |
using ServiceStack; | |
using ServiceStack.Configuration; | |
using ServiceStack.Host; | |
using ServiceStack.Host.Handlers; | |
using ServiceStack.Web; | |
using ServiceStack.Caching; | |
using ServiceStack.Data; | |
using ServiceStack.Text; | |
using ServiceStack.Auth; | |
using ServiceStack.Api.Swagger; | |
using ServiceStack.OrmLite; | |
using ServiceStack.OrmLite.SqlServer; | |
using ServiceStack.Razor; | |
using grm.service.model; | |
using grm.service.auth; | |
using grm.service.ServiceInterface; | |
namespace grm.service.api | |
{ | |
public class grmAppHost : AppSelfHostBase | |
{ | |
bool RecreateAuthTables = true; | |
string DataConnection = "...."; | |
static string license = "...."; | |
public grmAppHost() | |
: base("grm.service.api", typeof(APIAuthServices).Assembly, typeof(MyServices).Assembly) | |
{ // Base constructor requires a name and assembly to locate web service classes. | |
} | |
static grmAppHost() | |
{ // static constructor for License | |
; | |
ServiceStack.Licensing.RegisterLicense(license); | |
} | |
/// <summary> | |
/// Application specific configuration | |
/// This method should initialize any IoC resources utilized by your web service classes. | |
/// </summary> | |
/// <param name="container"></param> | |
public override void Configure(Container container) | |
{ | |
base.SetConfig(new HostConfig | |
{ | |
DefaultContentType = MimeTypes.Json, | |
ReturnsInnerException = true, | |
EnableFeatures = Feature.All.Remove(Feature.Metadata) | |
}); | |
JsConfig.EmitCamelCaseNames = true; | |
JsConfig.ExcludeTypeInfo = true; | |
JsConfig.EscapeUnicode = true; | |
Plugins.Add(new SwaggerFeature() { UseBootstrapTheme = false, UseCamelCaseModelPropertyNames = false }); | |
Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization")); | |
Plugins.Add(new RazorFormat()); | |
Plugins.Add(new SessionFeature()); | |
RawHttpHandlers.Add(httpReq => | |
httpReq.PathInfo == "/metadata" | |
? new RedirectHttpHandler() { RelativeUrl = "/swagger-ui" } : null); | |
ConfigureAuth(container); | |
} | |
private void ConfigureAuth(Funq.Container container) | |
{ | |
Plugins.Add(new AuthFeature( | |
() => new APIAuthUserSession(), | |
new[] { new APICredentialsAuthProvider() } | |
)); | |
//Default route: /register | |
Plugins.Add(new RegistrationFeature()); | |
container.Register<IDbConnectionFactory>(c => | |
new OrmLiteConnectionFactory(DataConnection, SqlServerDialect.Provider)); | |
container.Register<IUserAuthRepository>(c => | |
new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())); | |
var authRepo = (OrmLiteAuthRepository)container.Resolve<IUserAuthRepository>(); | |
if (RecreateAuthTables) | |
authRepo.DropAndReCreateTables(); | |
else | |
authRepo.InitSchema(); | |
var dbCacheClient = new OrmLiteCacheClient | |
{ | |
DbFactory = container.Resolve<IDbConnectionFactory>() | |
}; | |
dbCacheClient.InitSchema(); | |
container.Register<ICacheClient>(dbCacheClient); | |
container.Register<ISessionFactory>(c => new SessionFactory(c.Resolve<ICacheClient>())); | |
} | |
public void CreateUsers(string UserName, string password, string email, string FirstName, string LastName) | |
{ | |
try | |
{ | |
var client = new JsonServiceClient(Program.listeningOn); | |
var registerResponse = client.Post<RegisterResponse>(new Register | |
{ | |
DisplayName = UserName, | |
Email = email, | |
FirstName = FirstName, | |
LastName = LastName, | |
UserName = UserName, | |
Password = password, | |
AutoLogin = true | |
}); | |
} | |
catch (Exception err) | |
{ | |
} | |
finally | |
{ | |
} | |
} | |
protected override void Dispose(bool disposing) | |
{ | |
// Needed so that when the derived class tests run the same users can be added again. | |
base.Dispose(disposing); | |
} | |
public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext) | |
{ | |
return new MyServiceRunner<TRequest>(this, actionContext); | |
} | |
public override void OnUncaughtException(IRequest httpReq, IResponse httpRes, string operationName, Exception ex) | |
{ // | |
base.OnUncaughtException(httpReq, httpRes, operationName, ex); | |
} | |
} | |
public class MyServiceRunner<T> : ServiceRunner<T> | |
{ | |
public MyServiceRunner(IAppHost appHost, ActionContext actionContext) | |
: base(appHost, actionContext) | |
{ | |
} | |
public override object HandleException(IRequest request, T requestDto, Exception ex) | |
{ | |
APIException apiex = ex as APIException; | |
if (apiex != null) | |
{ | |
ResponseStatus rs = new ResponseStatus("APIException", apiex.message); | |
rs.Errors = new List<ResponseError>(); | |
rs.Errors.Add(new ResponseError()); | |
rs.Errors[0].ErrorCode = apiex.error_code.ToString(); | |
rs.Errors[0].Message = apiex.message; | |
rs.Errors[0].FieldName = request.PathInfo; | |
var errorResponse = DtoUtils.CreateErrorResponse(request, ex, rs); | |
Log.Error(ex.Message + "\r\n" + apiex.message); | |
return errorResponse; | |
} | |
else | |
return base.HandleException(request, requestDto, ex); | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Web; | |
using NUnit.Framework; | |
using ServiceStack; | |
using grm.service.model; | |
using grm.service.api; | |
using grm.service.ServiceInterface; | |
using System.Net; | |
using ServiceStack.Text; | |
using grm.service.auth; | |
namespace grm.service.tests | |
{ | |
[TestFixture] | |
public class UnitTests | |
{ | |
grmAppHost appHost; | |
string listeningOn = @"http://*:21092/"; | |
[TestFixtureSetUp] | |
public void TestFixtureSetUp() | |
{ | |
appHost = new grmAppHost(); | |
appHost.Init(); | |
appHost.Start(listeningOn); | |
} | |
[TestFixtureTearDown] | |
public void TestFixtureTearDown() | |
{ | |
appHost.Dispose(); | |
} | |
[Test] | |
public void APIAuthenticate_Login_Test() | |
{ | |
var client = new JsonServiceClient(@"http://localhost:21092/"); | |
APIAuthenticateResponse loginResponse = client.Post<APIAuthenticateResponse>(new APIAuthenticate | |
{ | |
UserName = "grmadmin", | |
Password = "z9", | |
RememberMe = false | |
}); | |
Assert.That(loginResponse, Is.Not.Null); | |
try | |
{ | |
myHelloResponse response = client.Post<myHelloResponse>(new myHello { Name = "World" }); | |
Assert.That(response.Result, Is.EqualTo(" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Web; | |
using ServiceStack; | |
using ServiceStack.OrmLite; | |
using ServiceStack.Auth; | |
using grm.service.model; | |
using grm.service.auth; | |
namespace grm.service.ServiceInterface | |
{ | |
public class MyServices : Service | |
{ | |
[Authenticate] | |
public object Post(myHello request) | |
{ | |
var typedSession = this.SessionAs<APIAuthUserSession>(); | |
//var userSession = this.GetSession(); | |
return new myHelloResponse { Result = "Hello, {0}!".Fmt(request.Name) }; | |
} | |
} | |
} | |
namespace grm.service.model | |
{ | |
[Route("/API.GRM.Tests/hello/{Name}", "POST", Summary = "hello")] | |
public class myHello : IReturn<myHelloResponse> | |
{ | |
public string Name { get; set; } | |
} | |
public class myHelloResponse | |
{ | |
public string Result { get; set; } | |
} | |
} | |
public class APIException : Exception | |
{ | |
public string message { get; set; } | |
public int error_code { get; set; } | |
public int detail_code { get; set; } | |
public string module { get; set; } | |
public override string Message | |
{ | |
get | |
{ | |
return message; | |
} | |
} | |
public APIException() | |
{ | |
} | |
public APIException(string msg) | |
{ | |
message = msg; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<packages> | |
<package id="NUnit" version="2.6.4" targetFramework="net45" /> | |
<package id="ServiceStack" version="4.0.38" targetFramework="net45" /> | |
<package id="ServiceStack.Client" version="4.0.38" targetFramework="net45" /> | |
<package id="ServiceStack.Common" version="4.0.38" targetFramework="net45" /> | |
<package id="ServiceStack.Interfaces" version="4.0.38" targetFramework="net45" /> | |
<package id="ServiceStack.OrmLite" version="4.0.38" targetFramework="net45" /> | |
<package id="ServiceStack.OrmLite.Sqlite.Windows" version="4.0.38" targetFramework="net45" /> | |
<package id="ServiceStack.Text" version="4.0.38" targetFramework="net45" /> | |
<package id="System.Data.SQLite.Core" version="1.0.94.0" targetFramework="net45" /> | |
</packages> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Configuration; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using ServiceStack; | |
using ServiceStack.Configuration; | |
using ServiceStack.Text; | |
using grm.service.api; | |
namespace grm.service.api | |
{ | |
public class Program | |
{ | |
public static string listeningOn = @"http://*:21092/"; | |
static void Main(string[] args) | |
{ | |
grmAppHost apphost = new grmAppHost(); | |
apphost.Init(); | |
apphost.Start(Program.listeningOn); | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment