Test Setup Failed
Push — master ( a9d37e...195d70 )
by Davide
01:16 queued 11s
created

RegisterController   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 250
Duplicated Lines 0 %

Importance

Changes 4
Bugs 1 Features 1
Metric Value
eloc 107
dl 0
loc 250
rs 10
c 4
b 1
f 1
wmc 14

7 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 58 4
A showRegistrationForm() 0 5 1
A userActivationMailSend() 0 16 1
A activateUserFromBackend() 0 35 3
A activateUser() 0 37 3
A __construct() 0 3 1
A create() 0 9 1
1
<?php
2
3
namespace App\Http\Controllers\Auth;
4
5
use App\Http\Controllers\Controller;
6
use App\Mail\UserActivation;
7
use App\Mail\UserActivationConfirmation;
8
use App\PostTranslation;
9
use App\User;
10
use DavideCasiraghi\LaravelEventsCalendar\Models\Country;
11
use Illuminate\Foundation\Auth\RegistersUsers;
12
use Illuminate\Http\Request;
13
use Illuminate\Support\Facades\App;
14
use Illuminate\Support\Facades\Hash;
15
use Illuminate\Support\Facades\Mail;
16
use Illuminate\Support\Str;
17
use Illuminate\Validation\Rule;
18
use Validator;
19
20
class RegisterController extends Controller
21
{
22
    /*
23
    |--------------------------------------------------------------------------
24
    | Register Controller
25
    |--------------------------------------------------------------------------
26
    |
27
    | This controller handles the registration of new users as well as their
28
    | validation and creation. By default this controller uses a trait to
29
    | provide this functionality without requiring any additional code.
30
    |
31
    */
32
33
    use RegistersUsers;
34
35
    /**
36
     * Where to redirect users after registration.
37
     *
38
     * @var string
39
     */
40
    protected $redirectTo = '/';
41
42
    // **********************************************************************
43
44
    /**
45
     * Create a new controller instance.
46
     *
47
     * @return void
48
     */
49
    public function __construct()
50
    {
51
        $this->middleware('guest')->except('activateUserFromBackend');
52
    }
53
54
    // **********************************************************************
55
56
    /**
57
     * Create a new user instance after a valid registration.
58
     *
59
     * @param  array  $data
60
     * @return \App\User
61
     */
62
    protected function create(array $data)
63
    {
64
        return User::create([
65
            'name' => $data['name'],
66
            'email' => $data['email'],
67
            'password' => Hash::make($data['password']),
68
            'country_id' => $data['country_id'],
69
            'description' => $data['description'],
70
            'accept_terms' => 'accepted',
71
        ]);
72
    }
73
74
    // **********************************************************************
75
76
    /**
77
     * Show the application registration form. - OVERRIDE to default function.
78
     *
79
     * @return \Illuminate\View\View
80
     */
81
    public function showRegistrationForm()
82
    {
83
        $countries = Country::getCountries();
84
85
        return view('auth.register', compact('countries'));
86
    }
87
88
    // **********************************************************************
89
90
    /**
91
     * Register new account. - OVERRIDE to default function.
92
     *
93
     * @param Request $request
94
     * @return \Illuminate\Http\RedirectResponse
95
     */
96
    protected function register(Request $request)
97
    {
98
        /** @var User $user */
99
100
        // Validate form datas
101
        $rules = [
102
            'name'     => 'required|string|max:255',
103
            'email'    => 'required|string|email|max:255|unique:users',
104
            'password' => 'required|string|min:6|confirmed',
105
            'country_id' => 'required|integer',
106
            'description' => 'required',
107
            'accept_terms' =>'required',
108
            //'g-recaptcha-response' => 'required|captcha',
109
            'recaptcha_sum_1' => [
110
                'required',
111
                Rule::in([$request->random_number_1 + $request->random_number_2]),
112
            ],
113
        ];
114
115
        $messages = [
116
            'recaptcha_sum_1.required' => 'Please solve the sum',
117
            'recaptcha_sum_1.in' => 'Your answer is not correct',
118
        ];
119
120
        $validator = Validator::make($request->all(), $rules, $messages);
121
        if ($validator->fails()) {
122
            return back()->withErrors($validator)->withInput();
123
        }
124
125
        try {
126
            $validatedData = $request->all();
127
            $validatedData['password'] = bcrypt($validatedData['password']);
128
            $validatedData['activation_code'] = Str::random(30).time();
129
            $validatedData['country_id'] = $request->country_id;
130
            $validatedData['description'] = $request->description;
131
            $validatedData['accept_terms'] = ($request->accept_terms == 'on') ? 1 : 0;
132
133
            // Create user
134
            $user = app(User::class)->create($validatedData);
0 ignored issues
show
Unused Code introduced by
The assignment to $user is dead and can be removed.
Loading history...
135
        } catch (\Exception $exception) {
136
            logger()->error($exception);
137
138
            return redirect()->back()->with('message', 'Unable to create new user.');
139
        }
140
141
        $countries = Country::getCountries();
142
143
        $mailDatas = [];
144
        $mailDatas['subject'] = 'New user registration';
145
        $mailDatas['name'] = $request->name;
146
        $mailDatas['email'] = $request->email;
147
        $mailDatas['country'] = $countries[$request->country_id];
148
        $mailDatas['description'] = $request->description;
149
        $mailDatas['activation_code'] = $validatedData['activation_code'];
150
151
        Mail::to(env('ADMIN_MAIL'))->send(new UserActivation($mailDatas));
152
153
        return redirect()->back()->with('message', __('auth.successfully_registered'));
154
    }
155
156
    // **********************************************************************
157
158
    /**
159
     * Activate the user with given activation code.
160
     * @param string $activationCode
161
     * @return \Illuminate\Http\RedirectResponse|string
162
     */
163
    public function activateUser(string $activationCode)
164
    {
165
        try {
166
            $user = app(User::class)->where('activation_code', $activationCode)->first();
167
            if (! $user) {
168
                return 'The code does not exist for any user in our system.';
169
            }
170
            $user->status = 1;
171
            $user->activation_code = null;
172
            $user->save();
173
            //auth()->login($user);
174
175
            // Get welcome message text
176
            //$locale = App::getLocale();
177
            $locale = 'en';
178
            $message = PostTranslation::
179
                where('title', 'Welcome email')
180
                ->where('locale', $locale)
181
                ->first();
182
183
            // Send to the user the confirmation about the activation of the account
184
            $mailDatas = [];
185
            $mailDatas['senderEmail'] = '[email protected]';
186
            $mailDatas['senderName'] = 'Global CI - Administrator';
187
            $mailDatas['subject'] = 'Activation of your Global CI account';
188
            $mailDatas['emailTo'] = $user->email;
189
            $mailDatas['name'] = $user->name;
190
            $mailDatas['body'] = $message->body ?? null;
191
192
            Mail::to($user->email)->send(new UserActivationConfirmation($mailDatas));
193
        } catch (\Exception $exception) {
194
            logger()->error($exception);
195
196
            return 'Whoops! something went wrong.';
197
        }
198
199
        return redirect()->to('/')->with('message', 'User succesfuly activated');
200
    }
201
202
    // **********************************************************************
203
204
    /**
205
     * Activate the user from the backend clicking on the Enable button in the user index view.
206
     * @param string $userId
207
     * @return \Illuminate\Http\RedirectResponse|string
208
     */
209
    public function activateUserFromBackend(string $userId)
210
    {
211
        try {
212
            $user = app(User::class)->where('id', $userId)->first();
213
            if (! $user) {
214
                return 'The code user id not exist for any user in our system.';
215
            }
216
            $user->status = 1;
217
            $user->save();
218
219
            // Get welcome message text
220
            //$locale = App::getLocale();
221
            $locale = 'en';
222
            $message = PostTranslation::
223
                where('title', 'Welcome email')
224
                ->where('locale', $locale)
225
                ->first();
226
227
            // Send to the user the confirmation about the activation of the account
228
            $mailDatas = [];
229
            $mailDatas['senderEmail'] = '[email protected]';
230
            $mailDatas['senderName'] = 'Global CI - Administrator';
231
            $mailDatas['subject'] = 'Activation of your Global CI account';
232
            $mailDatas['emailTo'] = $user->email;
233
            $mailDatas['name'] = $user->name;
234
            $mailDatas['body'] = $message->body ?? null;
235
236
            Mail::to($user->email)->send(new UserActivationConfirmation($mailDatas));
237
        } catch (\Exception $exception) {
238
            logger()->error($exception);
239
240
            return 'Whoops! something went wrong.';
241
        }
242
243
        return redirect()->to('/')->with('message', 'User succesfuly activated');
244
    }
245
246
    // **********************************************************************
247
248
    /**
249
     * Send the User activation mail to the Admin.
250
     *
251
     * @param  \Illuminate\Http\Request  $request
252
     * @return \Illuminate\Http\RedirectResponse
253
     */
254
    public function userActivationMailSend(Request $request)
255
    {
256
        $report = [];
257
258
        $report['senderEmail'] = '[email protected]';
259
        $report['senderName'] = 'Anonymus User';
260
        $report['subject'] = 'New user registration';
261
        $report['emailTo'] = env('ADMIN_MAIL');
262
263
        $report['name'] = $request->name;
264
        $report['email'] = $request->email;
265
        $report['message'] = $request->message;
266
267
        Mail::to($report['emailTo'])->send(new UserActivation($report));
268
269
        return redirect()->route('forms.contactform-thankyou');
270
    }
271
}
272