Files
cms_thermo_active/Step/Provider/ApplicationOAuthProvider.cs
T
Lucio Maranta fa485d902b * Added machine model, and new database relations
* Added first centralized database config and  added machine self-registration into db
* Fix database migration with new database
* Refactor
2018-01-17 10:24:18 +01:00

83 lines
3.2 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.Utils.Constants;
using static Step.Config.ServerConfig;
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
MachinesUsersModel 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;
}
// Find machine unique id
using (MachineController machineController = new MachineController())
{
MachineModel machineModel = machineController.GetMachineById(machineUser.MachineId);
// Add machine id
identity.AddClaim(new Claim(MACHINE_ID_KEY, machineModel.UniqueId));
}
// Add Role level key id
identity.AddClaim(new Claim(ROLE_LEVEL_KEY, machineUser.Role.Level.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;
}
}
}
}
}