Files
cms_thermo_active/Thermo.Active/Provider/ApplicationOAuthProvider.cs
T
2020-06-19 19:28:07 +02:00

100 lines
4.0 KiB
C#

using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Thermo.Active.Database.Controllers;
using Thermo.Active.Model.DatabaseModels;
using static Thermo.Active.Config.ServerConfig;
using static Thermo.Active.Model.Constants;
namespace Thermo.Active.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()));
}
var tiket = new AuthenticationTicket(identity, null);
tiket.Properties.IsPersistent = true;
// Create Token with identity data
context.Validated(tiket);
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.FirstOrDefault(c => c.Type == USER_ID_KEY);
var machineId = context.Identity.Claims.FirstOrDefault(c => c.Type == MACHINE_ID_KEY);
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);
}
}
}