PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/app/Http/Controllers/admin/Config/UsuarioController.php

https://bitbucket.org/sushimashi/ilendu
PHP | 412 lines | 297 code | 71 blank | 44 comment | 40 complexity | 20dc2cb2d1fcb6fe05580f8fe40de50c MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception
  1. <?php
  2. namespace App\Http\Controllers\Admin\Config;
  3. use Illuminate\Http\Request;
  4. use App\Http\Controllers\Controller;
  5. use App\User;
  6. use App\Role;
  7. use Illuminate\Support\Facades\Auth;
  8. use Illuminate\Support\Facades\Redirect;
  9. use Illuminate\Support\Facades\Storage;
  10. use Illuminate\Support\Facades\View;
  11. class UsuarioController extends Controller
  12. {
  13. public function __construct()
  14. {
  15. $this->middleware("permission:usuarios_ver")->only("index","show");
  16. $this->middleware("permission:usuarios_crear")->only("create", "store");
  17. $this->middleware("permission:usuarios_editar")->only("edit", "update");
  18. $this->middleware("permission:usuarios_eliminar")->only("destroy");
  19. View::share('titulo', "Usuarios");
  20. }
  21. /**
  22. * Display a listing of the resource.
  23. *
  24. * @return \Illuminate\Http\Response
  25. */
  26. public function index(Request $request)
  27. {
  28. if ($request->ajax()) {
  29. $usuario = [];
  30. $users = User::all();
  31. return response()->json($users);
  32. }
  33. return view('admin.config.usuarios.index');
  34. }
  35. /**
  36. * Show the form for creating a new resource.
  37. *
  38. * @return \Illuminate\Http\Response
  39. */
  40. public function create()
  41. {
  42. $roles = Role::all();
  43. return view('admin.config.usuarios.create', compact('roles'));
  44. }
  45. public function editUser($user_id, Request $request)
  46. {
  47. $user = User::find($user_id);
  48. try {
  49. $request->validate([
  50. 'first_name' => 'required',
  51. 'last_name' => 'required',
  52. 'email' => 'required|email',
  53. ]);
  54. if($request->filled('password')){
  55. $request->validate([
  56. 'password' => 'required|string|min:6'
  57. ]);
  58. $user->password = bcrypt( $request->password );
  59. }
  60. $user->update([
  61. 'first_name' => $request->first_name,
  62. 'last_name' => $request->last_name,
  63. 'email' => $request->email
  64. ]);
  65. return response()->json([
  66. 'success' => 'true',
  67. 'mensaje' => "Datos actualizados!"
  68. ]);
  69. } catch (Exception $e) {
  70. return response()->json([
  71. 'error' => $e->getMessage()
  72. ]);
  73. }
  74. }
  75. /**
  76. * Store a newly created resource in storage.
  77. *
  78. * @param \Illuminate\Http\Request $request
  79. * @return \Illuminate\Http\Response
  80. */
  81. public function usuariosSide(Request $request)
  82. {
  83. $data= [
  84. 'nombres' => 'required',
  85. 'apellidos' => 'required',
  86. ];
  87. $this->validate($request, $data);
  88. $usuario = User::findOrFail(auth()->user()->id);
  89. if($request->habilitar==true)
  90. {
  91. $usuario->estado=true;
  92. $usuario->save();
  93. return response()->json([
  94. 'success' => 'true',
  95. 'mensaje' => "Se habilito el usuario correctamente"
  96. ]);
  97. }else{
  98. $data = [
  99. 'nombres' => 'required',
  100. 'apellidos' => 'required'
  101. ];
  102. if ($request->password != "") {
  103. $data['password'] = 'required|same:repClave';
  104. }
  105. if ($request->anterior_email != $request->email) {
  106. $data['email'] = 'required|email|unique:users';
  107. }
  108. try {
  109. $usuario->fill($request->except('repClave', 'rol', 'habilitar','anterior_email','password','foto_perfil', 'cambiar_imagen'));
  110. if ($request->password != "") {
  111. $usuario->password = bcrypt($request->password);
  112. }
  113. $urlfinal="";
  114. if($request->cambiar_imagen == 1 && $request->_inicio == 1){
  115. $this->borrarImagenUsuario($usuario);
  116. if($request->input('foto_perfil')){
  117. $foto_perfil = $request->file('foto_perfil');
  118. $ruta = "img/foto_perfil/".uniqid().'.jpg';
  119. Storage::put('public/'.$ruta, $this->decode_imageCropit($request->input('foto_perfil')));
  120. $urlfinal = "/storage/$ruta";
  121. }
  122. $usuario->foto_perfil = $urlfinal;
  123. }
  124. $usuario->save();
  125. flash("Los datos fueron actualizado con éxito")->success();
  126. return response()->json([
  127. 'success' => 'true',
  128. 'mensaje' => "Los datos fueron actualizado con éxito"
  129. ]);
  130. } catch (\Exception $e) {
  131. return response()->json([
  132. 'error' => $e->getMessage()
  133. ]);
  134. }
  135. }
  136. }
  137. public function store(Request $request)
  138. {
  139. $this->validate($request, [
  140. 'nombres' => 'required',
  141. 'apellidos' => 'required',
  142. 'email' => 'required|email|unique:users',
  143. 'password' => 'required|same:repClave|min:6',
  144. 'rol' => 'required'
  145. ]);
  146. try {
  147. $urlfinal="";
  148. if($request->input('foto_perfil')){
  149. $foto_perfil = $request->file('foto_perfil');
  150. $ruta = "img/foto_perfil/".uniqid().'.png';
  151. Storage::put('public/'.$ruta, $this->decode_imageCropit($request->input('foto_perfil')));
  152. $urlfinal = "/storage/$ruta";
  153. }
  154. $user = new User();
  155. $user->fill($request->except('repClave', 'rol', 'foto_perfil'));
  156. $user->foto_perfil=$urlfinal;
  157. $user->password = bcrypt($request->password);
  158. $user->save();
  159. if($request->rol){
  160. $user->roles()->sync([$request->rol]);
  161. }else{
  162. $user->roles()->sync([]);
  163. }
  164. flash("El usuario <b>$request->nombres</b> fue creado con éxito")->success();
  165. return response()->json([
  166. 'success' => true,
  167. 'mensaje' => "El usuario <b>$request->nombres</b> fue creado con éxito"
  168. ]);
  169. } catch (\Exception $e) {
  170. return response()->json([
  171. 'error' => $e->getMessage()
  172. ]);
  173. }
  174. }
  175. private function decode_imageCropit($imageCropit){
  176. $imageCropit = str_replace('data:image/jpeg;base64,', '', $imageCropit);
  177. $imageCropit = str_replace(' ', '+', $imageCropit);
  178. return base64_decode($imageCropit);
  179. }
  180. /**
  181. * Display the specified resource.
  182. *
  183. * @param int $id
  184. * @return \Illuminate\Http\Response
  185. */
  186. public function show($id)
  187. {
  188. }
  189. /**
  190. * Show the form for editing the specified resource.
  191. *
  192. * @param int $id
  193. * @return \Illuminate\Http\Response
  194. */
  195. public function edit($id)
  196. {
  197. $roles = Role::all();
  198. $usuario = User::findOrFail($id);
  199. return view('admin.config.usuarios.edit', compact('roles','usuario'));
  200. }
  201. /**
  202. * Update the specified resource in storage.
  203. *
  204. * @param \Illuminate\Http\Request $request
  205. * @param int $id
  206. * @return \Illuminate\Http\Response
  207. */
  208. public function update(Request $request, $id)
  209. {
  210. $usuario = User::findOrFail($id);
  211. if($request->habilitar==true)
  212. {
  213. $usuario->estado=true;
  214. $usuario->save();
  215. return response()->json([
  216. 'success' => 'true',
  217. 'mensaje' => "Se habilito el usuario correctamente"
  218. ]);
  219. }else{
  220. $data = [
  221. 'nombres' => 'required',
  222. 'apellidos' => 'required'
  223. ];
  224. if ($request->password != "") {
  225. $data['password'] = 'required|same:repClave';
  226. }
  227. if ($request->anterior_email != $request->email) {
  228. $data['email'] = 'required|email|unique:users';
  229. }
  230. $this->validate($request, $data);
  231. try {
  232. $usuario->fill($request->except('repClave', 'rol', 'habilitar','anterior_email','password','foto_perfil', 'cambiar_imagen'));
  233. if ($request->password != "") {
  234. $usuario->password = bcrypt($request->password);
  235. }
  236. $urlfinal="";
  237. if($request->cambiar_imagen == 1 && $request->_inicio == 1){
  238. $this->borrarImagenUsuario($usuario);
  239. if($request->input('foto_perfil')){
  240. $foto_perfil = $request->file('foto_perfil');
  241. $ruta = "img/foto_perfil/".uniqid().'.jpg';
  242. Storage::put('public/'.$ruta, $this->decode_imageCropit($request->input('foto_perfil')));
  243. $urlfinal = "/storage/$ruta";
  244. }
  245. $usuario->foto_perfil = $urlfinal;
  246. }
  247. $usuario->save();
  248. if ($request->_inicio == 1) {
  249. $usuario->roles()->sync([$request->rol]);
  250. }
  251. flash("Los datos fueron actualizado con éxito")->success();
  252. return response()->json([
  253. 'success' => 'true',
  254. 'mensaje' => "Los datos fueron actualizado con éxito"
  255. ]);
  256. } catch (\Exception $e) {
  257. return response()->json([
  258. 'error' => $e->getMessage()
  259. ]);
  260. }
  261. }
  262. }
  263. private function borrarImagenUsuario($usuario){
  264. $fotoU = $usuario->foto_perfil;
  265. if($fotoU != "" || $fotoU != null){
  266. $fotoU = str_replace("storage","public",$fotoU);
  267. Storage::delete($fotoU);
  268. }
  269. }
  270. public function cambiarFoto($user_id, Request $request)
  271. {
  272. $usuario = User::findOrFail($user_id);
  273. try {
  274. $urlfinal="";
  275. // $this->borrarImagenUsuario($usuario);
  276. if($request->hasFile('foto_perfil')){
  277. $foto_perfil = $request->file('foto_perfil');
  278. $imgName = $foto_perfil->getClientOriginalName();
  279. $ruta = "img/profile/".$imgName;
  280. $foto_perfil->move(public_path("img/profile/"), $imgName);
  281. // Storage::put('public/'.$ruta, $this->decode_imageCropit($request->input('foto_perfil')));
  282. // $urlfinal = "/storage/$ruta";
  283. $urlfinal = $imgName;
  284. }
  285. $usuario->profile_img = $urlfinal;
  286. $usuario->save();
  287. return response()->json([
  288. 'success' => 'true',
  289. 'mensaje' => "Foto de perfil actualizada!",
  290. 'foto_url'=> "/img/profile/".$usuario->profile_img
  291. ]);
  292. } catch (\Exception $e) {
  293. return response()->json([
  294. 'error' => $e->getMessage()
  295. ]);
  296. }
  297. }
  298. /**
  299. * Remove the specified resource from storage.
  300. *
  301. * @param int $id
  302. * @return \Illuminate\Http\Response
  303. */
  304. public function destroy($id)
  305. {
  306. $user = Auth::user();
  307. $usuario = User::findOrFail($id);
  308. try {
  309. $result = $usuario->delete();
  310. if ($result == 1) {
  311. $this->borrarImagenUsuario($usuario);
  312. if ($usuario->id == $user->id) {
  313. Auth::logout();
  314. return response()->json([
  315. 'success' => true,
  316. 'mensaje' => "Se ha eliminado correctamente",
  317. 'cerrar_sesion'=>true
  318. ]);
  319. }else{
  320. return response()->json([
  321. 'success' => true,
  322. 'mensaje' => "Se ha eliminado correctamente",
  323. 'cerrar_sesion'=>false
  324. ]);
  325. }
  326. } else {
  327. return response()->json([
  328. 'error' => "Error al eliminar el usuario"
  329. ]);
  330. }
  331. } catch (\Exception $e) {
  332. $usuario->estado=0;
  333. $usuario->save();
  334. return response()->json([
  335. 'success' => true,
  336. 'mensaje' => "Se ha deshabilitado el usuario correctamente",
  337. 'cerrar_sesion'=>false
  338. ]);
  339. }
  340. }
  341. }