Just another WordPress site

Menu

Tag Archives: Leela

What use is a web admin if no one gets to login? It’s about as useful as giving each of our members a potato engraved with a special password that would give them and only them access to the secret Netsoc vault that exists beneath the catacombs of the Windle Building. So, this week, we’re dedicating an entire post to getting people registered and logged in – aren’t you lucky?

Controller

A controller in an MVC architecture, will be the main manipulator of data and requests from people. Whenever someone sends a request to our web app, we’ll be pushing it through our controller and figuring out where things are meant to go and what information needs to follow them. Some of the following methods in the
UserController class will be pretty sparse – maybe only a single line each – and that’s pretty standard for just creating generic views but we’ll also be handling the core of registering people and logging them in appropriately as well.

UserController.php

In
app/Http/Controllers/, create yourself a handy-dandy file called
UserController.php which will control everything to do with users. We should put in the following boiler-plate code:

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<?phpnamespaceApp\Http\Controllers;

// The namespace is the scope within this file exists

// These are all the classes/packages this control relies on

// The following are optional in general but we will use all of them

useView;

useAuth;

useResponse;

useRedirect;

useRequest;

useValidator;

useHash;

useApp\User;

useApp\Setting;

// Extend the generic Controller class - a mandatory step

classUserControllerextendsController

{

}

login() and register()

These two are just there to render views. They don’t add any information and they don’t really control anything – they’re just vehicles for our login and register forms. The code’s fairly straightforward and it just involves adding two methods to the UserController class.

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

/**

* Render registration view

* @return VIEW register

*/

publicfunctionregister(){

if(Auth::check()){

// If user is logged in, send 'em home

returnRedirect::route('home');

}

// Render the Register view

returnView::make('auth.register');

}

/**

* Render login view

* @return VIEW login

*/

publicfunctionlogin(){

if(Auth::check()){

// If user is logged in, send 'em home

returnRedirect::route('home');

}

// Render the Login view

returnView::make('auth.login');

}

We’ll be setting up the view files that correspond to these commands a little later but, before then, let’s move on to another handy function before the pièce de résistance.

handleLogin()

What’s going to happen in this method, is the user’s going to submit the form in
login() which will forward all the data to
handleLogin() which will process the data, assess whether you’re you and log you in if you are or flag an error on the form.

For starters, we just need to get the information from the form. Let’s start our method and filter our data to be only the fields we’re expecting –
email and
password.

136

137

138

139

140

141

142

143

/**

* Log a user into the system

* @return REDIRECT home

*/

publicfunctionhandleLogin(){

// Filter allowed data

$data=Request::only(['email','password']);

}

The next step is to validate that input and make sure it is what it should be, however the only thing we’re going to be looking for is that the two fields are definitely filled in.

PHP

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

$data=Request::only(['email','password']);

// Validate user input

$validator=Validator::make(

$data,

[

'email'=>'required',

'password'=>'required',

]

);

if($validator->fails()){

// If validation fails, send back to the login form with errors

returnRedirect::route('login')->withErrors($validator)->withInput();

}

The Validator within Laravel is really nice and easy to work with. We pass in our data from the form and set out a series of parameters to check against the data. This one is just a simple example on making sure that the fields we need have been filled in. Then, we call the
fails() method from the validator and check if our data is okay.

If the validator fails, we’re then going to send the person back to the login page along with what they put into the form (
->withInput()) and with the errors we got during validation (
->withErrors($validator)).

Now, for the meat of the method! We’re actually going to check the user credentials and log the user in. Are you as excited as I am? (It’s a prerequisite of continuing so you’d better be!)

store()

Oh boy, oh boy, oh boy! Here we are, creating the user account. This bit will incorporate a lot of the
handleLogin() method and show you how models are created/instantiated in Laravel.

First, let’s take in the form info and validate it.

PHP

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

/**

* Creates a new user

* Data should be POSTed to this function only

* @return REDIRECT home

*/

publicfunctionstore(){

// Only allow following fields to be submitted

$data=Request::only([

'email',

'password',

'password_confirmation',

'student_id',

'graduation_year',

'course',

'name'

]);

// Validate all input

$validator=Validator::make($data,[

'email'=>'required|unique:users|min:5',

'student_id'=>'numeric|required|unique:users',

'password'=>'required|confirmed|min:5',

'graduation_year'=>'required|numeric|digits:4',

'course'=>'required',

'name'=>'required'

]);

if($validator->fails()){

// If validation fails, redirect back to

// registration form with errors

returnRedirect::back()

->withErrors($validator)

->withInput();

}

}

You’ll notice we’ve got a lot more validation parameters in this one. For example, this time we’re being much stricter on our email. From left to right: 1) The email is required. 2) The email must be unique in the
users table. 3) It must be a minimum of 5 characters. I won’t go through the others so if you’d like to see all of the available rules, check out the documentation on the matter.

Once everything’s good to go, we’ll pass the data to the
User model and create our user account (whoop whoop!).

PHP

133

134

// Create new user locally

$newUser=User::create($data);

Is… is that it? Uh…

I know, it doesn’t look like much but, because our form names are the same names as our MySQL column names, we simply pass the verified data into the model and it then inserts the relevant info into our database. It’s a single line and it’s the minimum you’ll need for this function.

You’ll notice at the end there that I’ve also anticipated something going wrong in the creation process. If that happens we redirect back to the last page the user was on (the registration form) with their info (excluding their password).

The Whole Thing

There’s a lot of bits and pieces here so I’ve put together a view of the whole file for you to copy and paste into your favourite editor. If you’re not interested in this, skip to the Views below.

Views

All of our views for this particular post will happen within the
resources/views/auth folder. The
auth folder is custom-made, so go ahead and create that first. Then move onto our view files. Remember, how we render these views was taken care of in the Controller above.

login.blade.php

To begin all of our views, we’re going to be extending one of our default layouts we made in the last segment.

login.blade.php

PHP

1

@extends('layouts.default')

Next, we want to add a couple custom classes to our
<body>. The first will be to leverage MaterializeCSS’ vertical alignment magic. The second, will be so we can accurately scope custom styling to just our login page.

PHP

3

@section('body-class')valign-wrapper login@endsection

For the actual form, we need a section in our content that always applies our
valign class for proper alignment on the screen. If you don’t understand the grid system or styling classes I’ve added, please have a sconse of the MaterializeCSS documentation to fully understand what’s going on (there’s kind of just too much to explain really).

XHTML

5

6

7

8

9

10

11

@section('content')

<main class="row container">

<section class="card-panel white col l6 offset-l3 s12 valign">

</section>

</main>

@stop

Inside that
<section>, we’re gonna put our logo, a title and somewhere for our errors to show when things go wrong.

XHTML

8

9

10

11

12

13

14

15

<img src="{{ URL::to('/') }}/images/logo.png"class="form-logo"/>

<h3 class="center-align"> Login </h3>

<!-- All our errors will go in here as a handy-dandy list -->

@foreach($errors->all() as $message)

<li>{{ $message }}</li>

@endforeach

The
URL::to('/') is used to get an absolute URL for the root of our application. This just means that we can easily move around the code from folder to folder or server to server and still be confident all the links and images will work.

The final step is to add the form. We’ll be using
{!! and
!!} around these blade elements as they need to be printed literally so as to avoid the blade engine automatically stripping out the HTML code – that would be kinda bad.

App.less

Remember the
app.less file in
resources/assets/less? No, well, we’re going to need to add some style to our project. Otherwise, things are gonna look a little shitty. A lot of this is just styling and I’m assuming that because you have a grasp on HTML, you’re also familiar with some CSS so I won’t be explaining every design decision but have included them for the sake of completeness.

I’m leveraging LESS variables so that we can keep a consistent style throughout the application. For the most part, it’s just going to be some colours and our fonts. You can do much more complicated things (like mix-ins) but we only need some really simple stuff here.

Laravel provides an implementation of the Blade templating engine which lets us define generic templates for our data and page layouts. What I’m going to cover in this post is some really basic templates which we’ll base the rest of our designs off. We’re going to need two different layouts: a default full-width layout and a default with sidebar layout. Breaking those down further, we’ll also need a template for the header, the footer and the sidebar itself. So, let’s get to it!

(Note: I am going to assume a working knowledge of HTML5)

Templates

To begin with anyway, all of our generic layout templates will live in
resources/views/layouts so we can extend them later for more specific templates. As well as this, all of our files will end in
.blade.php so signify that they are blade templates. If you’d like to read more about templating, I recommend having an ol’ sconce at the laravel documentation on the subject.

Header.blade.php

To begin with, we’re going to need a
&lt;head&gt; section, as well as somewhere to begin our
&lt;body&gt; too. So here’s some generic boilerplate HTML to begin our project:

The first kind of laravel-specific thing we’re going to include is a
@yield() for the site title.
@yield() takes one mandatory parameter and one optional parameter as such:
@yield('some_name','default_value). The name can be anything you like which we’ll refer to in later templates. The purpose of
@yield() is to set out placeholders for content/sections later on.

All the below is doing is saying that some of our pages will have their own title but, if not, use the SITE_TITLE variable in our .env file as the default.

XHTML

4

<title>@yield('title', env('SITE_TITLE'))</title>

Next, we’re gonna need a by of shtyling to make our website look pretty. So then, let’s include some required CSS for

FontAwesome – just some really awesome icons I prefer using to Materialize’s icons

Later on, we might need to include some extra stylesheets or add some extra tags to the head because Open Graph Tags are something every budding web developer should know (seriously, don’t build a project without them – it’s practically unshareable that way).

As such, we’re going to define two extra placeholder sections: one for extra CSS and one for extra header content.

XHTML

15

16

17

@yield('extra-css')

@yield('extra-head')

And, finally, we’re gonna add a placeholder for a custom body class so we can properly scope our styling.

Default.blade.php

Those two are all well and good but we don’t want to repeat ourselves and we’ll definitely want to deviate from the layout so something we’ll do here is stitch the two files together and put in our placeholder for a “content” section. This is the entire default.blade.php file:

1

2

3

4

5

@include('layouts.header')

@yield('content')

@include('layouts.footer')

Sidebar.blade.php

Here’s that fabled sidebar I just mentioned. When a user is logged in, they’re much more accustomed to a dashboard view of things for technical-type things (like AWS, Azure, facebook advertising, etc.). As such, there’s only one thing we absolutely need to adhere to in order to make sure navigation feels familiar – put our navigation in the sidebar. With Materialize, this is actually dead simple to do.

Below is the entire code of the sidebar but I’ve put in some helpful comments to help explain certain things. You don’t need to worry too much about the individual class names but if you’d like to learn more, you can check out the Materialize documentation.

default-with-sidebar.blade.php

As with our other default template, we’re just going to stitch together some of our base components and create a nice simple default layout for the admin area. It’s the same as before, we’re just going to use Materialize’s columns to define some constraints for the main content section and make sure it doesn’t ruin our view.

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

@include('layouts.header')

<!-- Our entire page will be one row -->

<div class="row with-sidebar">

<!-- Our side nav has a natural column width

so we won't define one here -->

@include('layouts.sidebar')

<!-- The main content will need to be constrained

so it doesn't overflow behind the sidebar -->

<main class="col offset-l3 l9 s12">

@yield('content')

</main>

</div>

@include('layouts.footer')

Wrap-Up

Well, that’s week 3 down and I hope you’re learning lots. These are just the base on top of which we build all of our views. It’s really simple to work with views within Laravel. I should have mentioned it above but anything within two sets of curly braces is executed as if it were a PHP command then echoed out (displayed on the web page). Later, we’ll pass data from our controllers to our views and fill our templates with actual, real-life data :O

Join us next week for another exciting episode of “Evan talks to himself about how he built NetsocAdmin so he doesn’t have to write actual documentation”!

What is IRC?

IRC (Internet Relay Chat) is a chat protocol that allows us to communicate with all the networking/computer societies on the Intersocs network.

What The Fuck Is Intersocs?

Intersocs is a network of IRC “peers” that facilitates communication with the following societies:

Redbrick (DCU Netsoc)

TCD Netsoc

DUCSS (Dublin University Computer Science Society)

Skynet (UL Netsoc)

DIT Netsoc

UCD Netsoc (Coming Soon…)

NCI Netsoc (Coming Soon…)

NUIG CompSoc (Coming Soon…)

Logging in (SSH)

The first thing we’re going to need to do, is actually log into Leela (our primary user server). To do this, we’ll use Secure Shell(SSH).

Mac OSX / Linux

SSH clients come preinstalled on all versions of Mac OSX and Linux. To start using it, open up your terminal/console/command prompt of some kind, replace
USERNAME with your username and execute the following command:

1

2

3

ssh USERNAME@leela.netsoc.co

You’ll then be prompted for your password.

Windows

You’ll need to install some kind of SSH client for windows. We recommend using PuTTY.

Screen

The
screen command is what’s known as a \texit{terminal multiplexer} (or “mux”). What it does is it creates multiple windows for you to run different commands or leave commands running. It’s useful if you want to leave something connected but still want to be able to log out.

We’re going to use screen to keep a permanently connected irc client running for whenever you log in.

Our
irc command

When you log in, you’re automatically given a
.profile file with some predefined commands. One of those commands is
irc.

What happens is that when you log in, we automagically create a screen for you (if it isn’t running already) and we alias} “\inlinecode{irc” to attach you to that screen.

Manually Creating A Screen

You can also manually create screens yourself. Below is part of the example
.profile we give everyone. You only need to concern yourself with lines 2 and 5.

1

2

3

4

5

6

7

if!screen-list|grep-q"irc";then

screen-dmS irc bash-c'weechat'

fi

alias irc="screen -r irc"

screen-dmS irc bash-c'weechat'

Here we’re:

creating a screen

telling it to run in the background

naming it “irc”

executing the command
bash-c'weechat' – you can leave this blank and it will run a bash shell by default

alias irc="screen -r irc"

This line simply aliases the command
ircx to command
screen-rirc. We can attach ourselves to any named screen using the syntax
screen-rNAME

Okay… I want to leave. Now what?

To detach from any screen, simply hit
ctrl +
a +
d and you’ll be returned to your original terminal.

IRC

This is it, the bit you’ve all been waiting for.

Once you’ve connected to your IRC screen (that’s running Weechat), you will need to connect to our netsoc server with the following command:

1

2

3

/connect netsoc.co

Congrats, you’re now connected! Start out by typing
/join uccnetsoc and
/join intersocs

When you’re done

Simply
ctrl +
a +
d to detach from your screen and type
logout to leave the server.