authd/src/authd.cr

97 lines
1.5 KiB
Crystal
Raw Normal View History

require "jwt"
require "ipc"
require "./user.cr"
require "./group.cr"
module AuthD
enum RequestTypes
2018-12-19 13:57:48 +01:00
GetToken
AddUser
end
enum ResponseTypes
2018-12-19 13:57:48 +01:00
Ok
MalformedRequest
InvalidCredentials
InvalidUser
end
class GetTokenRequest
JSON.mapping({
# FIXME: Rename to "login" for consistency.
login: String,
password: String
})
end
2018-12-19 13:54:19 +01:00
class AddUserRequest
JSON.mapping({
login: String,
password: String,
uid: Int32?,
gid: Int32?,
home: String?,
shell: String?
})
end
class Client < IPC::Client
property key : String
def initialize
@key = ""
initialize "auth"
end
def get_token?(login : String, password : String)
2018-12-19 13:57:48 +01:00
send RequestTypes::GetToken.value.to_u8, {
:login => login,
:password => password
}.to_json
response = read
2018-12-19 13:57:48 +01:00
if response.type == ResponseTypes::Ok.value.to_u8
response.payload
else
nil
end
end
2018-12-19 13:54:19 +01:00
def send(type : RequestTypes, payload)
send type.value.to_u8, payload
end
def decode_token(token)
user, meta = JWT.decode token, @key, "HS256"
user = AuthD::User.from_json user.to_json
{user, meta}
end
2018-12-19 13:54:19 +01:00
# FIXME: Extra options may be useful to implement here.
def add_user(login : String, password : String) : AuthD::User | Exception
2018-12-19 13:57:48 +01:00
send RequestTypes::AddUser, {
2018-12-19 13:54:19 +01:00
:login => login,
:password => password
}.to_json
response = read
pp! response.type
case ResponseTypes.new response.type.to_i
2018-12-19 13:57:48 +01:00
when ResponseTypes::Ok
2018-12-19 13:54:19 +01:00
AuthD::User.from_json response.payload
else
Exception.new response.payload
end
end
end
end