1 module hunt.framework.auth.SimpleUserService; 2 3 import hunt.framework.auth.UserDetails; 4 import hunt.framework.auth.UserService; 5 6 import hunt.framework.config.AuthUserConfig; 7 import hunt.framework.provider.ServiceProvider; 8 import hunt.logging; 9 10 import std.digest.sha; 11 12 13 /** 14 * Retrieve user details from a local config file. 15 */ 16 class SimpleUserService : UserService { 17 18 private AuthUserConfig _userConfig; 19 20 this() { 21 _userConfig = serviceContainer.resolve!(AuthUserConfig)(); 22 } 23 24 private AuthUserConfig.Role getRole(string name) { 25 foreach(AuthUserConfig.Role r; _userConfig.roles) { 26 if(r.name == name) return r; 27 } 28 29 return null; 30 } 31 32 UserDetails authenticate(string name, string password) { 33 34 foreach(AuthUserConfig.User user; _userConfig.users) { 35 if(user.name != name || user.password != password) 36 continue; 37 38 UserDetails userDetails = new UserDetails(); 39 userDetails.name = name; 40 // userDetails.password = password; 41 userDetails.salt = getSalt(name, user.password); 42 43 // roles 44 foreach(string roleName; user.roles) { 45 AuthUserConfig.Role role = getRole(roleName); 46 if(role !is null) { 47 userDetails.roles ~= role.name; 48 userDetails.permissions ~= role.permissions; 49 } else { 50 warning("The role is not defined: %s", roleName); 51 } 52 } 53 54 return userDetails; 55 } 56 return null; 57 } 58 59 UserDetails getByName(string name) { 60 foreach(AuthUserConfig.User user; _userConfig.users) { 61 if(user.name != name) 62 continue; 63 64 UserDetails userDetails = new UserDetails(); 65 userDetails.name = name; 66 // userDetails.password = user.password; 67 userDetails.salt = getSalt(name, user.password); 68 69 // roles 70 foreach(string roleName; user.roles) { 71 AuthUserConfig.Role role = getRole(roleName); 72 if(role !is null) { 73 userDetails.roles ~= role.name; 74 userDetails.permissions ~= role.permissions; 75 } else { 76 warning("The role is not defined: %s", roleName); 77 } 78 } 79 return userDetails; 80 } 81 return null; 82 } 83 84 UserDetails getById(ulong id) { 85 return null; 86 } 87 88 string getSalt(string name, string password) { 89 string userSalt = name; 90 auto sha256 = new SHA256Digest(); 91 ubyte[] hash256 = sha256.digest(password~userSalt); 92 return toHexString(hash256); 93 } 94 95 }