/
Digest.hx
69 lines (60 loc) · 1.72 KB
/
Digest.hx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package ufront.auth.adapter;
import thx.error.Error;
import ufront.auth.AuthResult;
import ufront.auth.AuthResultMessage;
import ufront.auth.IAuthAdapter;
import thx.error.NullArgument;
import thx.sys.FileSystem;
import thx.sys.io.File;
import haxe.io.Eof;
import thx.util.Message;
using StringTools;
class Digest implements IAuthAdapter<Identity>
{
public var filename : String;
public var realm : String;
public var username : String;
public var password : String;
public function new(?filename : String, ?realm : String, ?username : String, ?password : String)
{
this.filename = filename;
this.realm = realm;
this.username = username;
this.password = password;
}
public function authenticate()
{
NullArgument.throwIfNull(filename);
NullArgument.throwIfNull(realm);
NullArgument.throwIfNull(username);
NullArgument.throwIfNull(password);
if(!FileSystem.exists(filename))
throw new Error("authentication file '{0}' does not exists", filename);
var identity = { realm : realm, username : username };
var id = username + ":" + realm;
var file = File.read(filename, false);
var close = function(message) {
file.close();
return new AuthResult(message, identity);
};
try
{
while(true)
{
var line = file.readLine().trim();
if(line.startsWith(id))
{
if(line.substr(-32) == haxe.Md5.encode(username + ":" + realm + ":" + password))
return close(Success);
else
return close(InvalidCredential(new Message('password incorrect')));
}
}
} catch(e : Eof){}
return close(IdentityNotFound(new Message("username '{0}' and realm '{1}' combination not found", [username, realm])));
}
}
typedef Identity = {
realm : String,
username : String
}