source: StockMaster/Controllers/UserController.cs@ dfe03b8

main
Last change on this file since dfe03b8 was dfe03b8, checked in by Ceyda <ceyda.huseini@…>, 4 days ago

Initialize StockMaster project

  • Property mode set to 100644
File size: 5.1 KB
Line 
1using Microsoft.AspNetCore.Mvc;
2using StockMaster.Data;
3using StockMaster.Models;
4using StockMaster.Services;
5using Microsoft.EntityFrameworkCore;
6using System.Threading.Tasks;
7
8namespace StockMaster.Controllers
9{
10 public class UserController : BaseController
11 {
12 private readonly StockDbContext _context;
13 private readonly IAuthService _authService;
14
15 public UserController(StockDbContext context, IAuthService authService)
16 {
17 _context = context;
18 _authService = authService;
19 }
20
21 public async Task<IActionResult> Index()
22 {
23 var users = await _context.Users
24 .OrderBy(u => u.Username)
25 .ToListAsync();
26 return View(users);
27 }
28
29 [HttpGet]
30 public IActionResult Create()
31 {
32 return View();
33 }
34
35 [HttpPost]
36 public async Task<IActionResult> Create(User user, string PlainPassword)
37 {
38
39 if (string.IsNullOrEmpty(PlainPassword))
40 {
41 ModelState.AddModelError("PlainPassword", "Password is required");
42 return View(user);
43 }
44
45
46 ModelState.Remove("Password");
47
48 if (ModelState.IsValid)
49 {
50 try
51 {
52 var result = await _authService.CreateUserAsync(user, PlainPassword);
53 if (result)
54 {
55 TempData["Success"] = "User created successfully";
56 return RedirectToAction("Index");
57 }
58 ModelState.AddModelError("", "Failed to create user. Username or email may already exist.");
59 }
60 catch
61 {
62 ModelState.AddModelError("", "Failed to create user");
63 }
64 }
65
66 return View(user);
67 }
68
69 [HttpGet]
70 public async Task<IActionResult> Edit(int id)
71 {
72 var user = await _context.Users.FindAsync(id);
73 if (user == null)
74 return NotFound();
75
76 return View(user);
77 }
78
79
80 [HttpPost]
81 public async Task<IActionResult> Edit(User user, string PlainPassword)
82 {
83 ModelState.Remove("Password");
84 ModelState.Remove("CreatedAt");
85 ModelState.Remove("PlainPassword");
86
87 if (!ModelState.IsValid)
88 {
89 var errors = ModelState.Values.SelectMany(v => v.Errors);
90 foreach (var error in errors)
91 {
92 ModelState.AddModelError("", "Validation Error: " + error.ErrorMessage);
93 }
94 return View(user);
95 }
96
97 try
98 {
99 var existingUser = await _context.Users.FindAsync(user.UserId);
100
101 if (existingUser == null)
102 {
103 return NotFound();
104 }
105
106
107 var usernameExists = await _context.Users.AnyAsync(u => u.Username == user.Username && u.UserId != user.UserId);
108 if (usernameExists)
109 {
110 ModelState.AddModelError("Username", "This username is already taken.");
111 return View(user);
112 }
113
114
115 existingUser.Username = user.Username;
116 existingUser.FullName = user.FullName;
117 existingUser.Email = user.Email;
118 existingUser.Role = user.Role;
119 existingUser.IsActive = user.IsActive;
120
121
122 if (!string.IsNullOrEmpty(PlainPassword))
123 {
124 existingUser.Password = BCrypt.Net.BCrypt.HashPassword(PlainPassword);
125 }
126
127 _context.Users.Update(existingUser);
128 await _context.SaveChangesAsync();
129
130 TempData["Success"] = "User updated successfully";
131 return RedirectToAction("Index");
132 }
133 catch (Exception ex)
134 {
135 ModelState.AddModelError("", "System Error: " + ex.Message);
136 return View(user);
137 }
138 }
139
140 [HttpPost]
141 public async Task<IActionResult> Delete(int id)
142 {
143 try
144 {
145 var user = await _context.Users.FindAsync(id);
146 if (user != null)
147 {
148 var currentUserId = HttpContext.Session.GetInt32("UserId");
149 if (user.UserId == currentUserId)
150 {
151 TempData["Error"] = "You cannot delete your own account";
152 return RedirectToAction("Index");
153 }
154
155 _context.Users.Remove(user);
156 await _context.SaveChangesAsync();
157 TempData["Success"] = "User deleted successfully";
158 }
159 }
160 catch
161 {
162 TempData["Error"] = "Cannot delete user. It may be in use.";
163 }
164 return RedirectToAction("Index");
165 }
166 }
167}
Note: See TracBrowser for help on using the repository browser.