Files
cms_thermo_active/Step/Provider/ApplicationOAuthProvider.cs
T
Lucio Maranta fb908a8903 Refactor constants and functionality name
Added signalR override management
Fix head configuration
2018-03-15 14:46:14 +01:00

97 lines
3.8 KiB
C#

using System;
using System.Threading.Tasks;
using Microsoft.Owin.Security.OAuth;
using Step.Database.Controllers;
using Step.Model.DatabaseModels;
using System.Security.Claims;
using static Step.Model.Constants;
using static Step.Config.ServerConfig;
using System.Linq;
namespace Step.Provider
{
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// Validate client
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (UsersController usersController = new UsersController())
{
try
{
// Check if credentials are correct
UserModel user = usersController.FindByUsernameAndPassword(context.UserName, context.Password);
// If not
if (user == null)
{
// Return 401
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
// Create a new Identity and insert custom claims
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
// Add claims to token
identity.AddClaim(new Claim(USER_ID_KEY, user.UserId.ToString()));
using (MachinesUsersController machinesUsersController = new MachinesUsersController())
{
// Check if user can access to the machine
MachineUserModel machineUser = machinesUsersController.FindByUserId(MachineConfig.MachineId, user.UserId);
if (machineUser == null)
{
// Return 401 bad request
context.SetError("invalid_grant", "User has no access to this machine");
return;
}
// Add machine id
identity.AddClaim(new Claim(MACHINE_ID_KEY, machineUser.MachineId.ToString()));
}
// Create Token with identity data
context.Validated(identity);
await base.GrantResourceOwnerCredentials(context);
return;
}
catch (Exception ex)
{
// Return 401 bad request
context.SetError("invalid_grant", ex.Message);
return;
}
}
}
public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)
{
// Find userId and machineId from Claims
var userId = context.Identity.Claims.Where(c => c.Type == USER_ID_KEY).SingleOrDefault();
var machineId = context.Identity.Claims.Where(c => c.Type == MACHINE_ID_KEY).SingleOrDefault();
using(MachinesUsersController machinesUsersController = new MachinesUsersController())
{
// Find machineUser Id from database by machineId and userId
MachineUserModel machineUser = machinesUsersController.FindByUserId(Convert.ToInt32(machineId.Value), Convert.ToInt32(userId.Value));
using (SessionsController sessionsController = new SessionsController())
{
// Create new user session
sessionsController.Create(machineUser.MachineUserId, context.AccessToken);
}
}
return base.TokenEndpointResponse(context);
}
}
}