Advertisement
Guest User

Untitled

a guest
Dec 5th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Data.SqlClient;
  6. using System.Text;
  7. using System.Security.Cryptography;
  8. using RCKlubben.Models;
  9.  
  10. namespace RCKlubben.Factories
  11. {
  12. public class UserFactory : AutoFac<User>
  13. {
  14. public static string HashPassword(string password)
  15. {
  16. // Get byte values for each character in password and store in byte array.
  17. byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
  18.  
  19. // Hash the bytes
  20. SHA256 sha = new SHA256Managed();
  21. var computedPassword = sha.ComputeHash(passwordBytes);
  22.  
  23. // Format the hashed bytes back to a string.
  24. var hashedPassword = string.Empty;
  25. foreach (var b in computedPassword)
  26. {
  27. hashedPassword += String.Format("{0:x2}", b);
  28. }
  29.  
  30. return hashedPassword;
  31. }
  32.  
  33. public User Login(string username, string password)
  34. {
  35. Mapper<User> mapper = new Mapper<User>();
  36.  
  37. using (var cmd = new SqlCommand("SELECT * FROM [user] WHERE Username=@Username AND Password=@Password",
  38. Conn.CreateConnection()))
  39. {
  40. cmd.Parameters.AddWithValue("@Username", username);
  41. cmd.Parameters.AddWithValue("@Password", HashPassword(password));
  42.  
  43. var r = cmd.ExecuteReader();
  44. User user = new User();
  45.  
  46. if (r.Read())
  47. {
  48. user = mapper.Map(r);
  49. }
  50.  
  51. r.Close();
  52. cmd.Connection.Close();
  53.  
  54. if (user.Id > 0)
  55. {
  56. // Set the users session so he/she is logged in.
  57. HttpContext.Current.Session["UserId"] = user.Id;
  58. }
  59.  
  60. return user;
  61. }
  62. }
  63.  
  64. public User Login(User user)
  65. {
  66. return Login(user.Username, user.Password);
  67. }
  68.  
  69. public User Register(string username, string password)
  70. {
  71. // Create the new user model.
  72. User user = new User
  73. {
  74. Username = username,
  75. Password = HashPassword(password),
  76. };
  77.  
  78. var id = Insert(user);
  79.  
  80. return Get(id);
  81. }
  82.  
  83. public User Register(User user)
  84. {
  85. return Register(user.Username, user.Password);
  86. }
  87. }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement