Thursday , 14 December 2017
Home » Tutorial » Buat Login Yii Framework 2.0 Basic Dengan Database MySQL
Buat Login Yii Framework 2.0 Basic Dengan Database MySQL

Buat Login Yii Framework 2.0 Basic Dengan Database MySQL

Setelah berhasil menginstall, sekarang saatnya kita buat database user.

Buat koneksi ke database.

Buka folder file db.php di folder config

[sourcecode language=”html”]<?php

return [
‘class’ => ‘yii\db\Connection’,
‘dsn’ => ‘mysql:host=localhost;dbname=<strong>yii2dasar</strong>’,
‘username’ => ‘root’,
‘password’ => ‘rahasia’,
‘charset’ => ‘utf8’,
];[/sourcecode]

Buat database dengan nama yii2dasar, kemudian klik menu SQL di phpmyadmin dan masukkan code berikut

[sourcecode language=”html”]– phpMyAdmin SQL Dump
— version 4.2.11
— http://www.phpmyadmin.net

— Host: 127.0.0.1
— Generation Time: May 02, 2015 at 11:55 AM
— Server version: 5.6.21
— PHP Version: 5.6.3

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;


— Database: `yii2dasar`

— ——————————————————–


— Table structure for table `user`

CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL,
  `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `first_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `last_name` int(100) NOT NULL,
  `id_skpd` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `id_bagian` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `id_atasan` varchar(18) COLLATE utf8_unicode_ci NOT NULL,
  `auth_key` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `password_hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password_reset_token` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `status` smallint(6) NOT NULL DEFAULT ’10’,
  `created_at` int(11) NOT NULL,
  `updated_at` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1234 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


— Dumping data for table `user`

INSERT INTO `user` (`id`, `username`, `first_name`, `last_name`, `id_skpd`, `id_bagian`, `id_atasan`, `auth_key`, `password_hash`, `password_reset_token`, `email`, `status`, `created_at`, `updated_at`) VALUES
(6, ‘demo’, ‘Demo, S.Kom.’, 0, ‘1.20.03.’, ‘1’, ‘196312311993031151’, ‘HSDsFTEPwKkx34lNhy3PaFijUhHUiM88’, ‘$2y$13$OqdCb2oNxaIUMdgNGxda0.J3X2dGUiIrhfA7IoPKJ55aqgBS0c1dm’, NULL, ‘demo@gmail.com’, 10, 1429367734, 1429367734),
(1233, ‘admin’, ‘Admin, S.Kom.’, 0, ‘1.15.01.’, ‘1’, ‘196312311993031151’, ‘d-5OBWbcTGb6jn6cNDt_O1I9eK54a6zU’, ‘$2y$13$cFrJU0eJ8CH5cGd.wHpase6HIChMdr4zvNzSJaIWs0aUPP3sENHSC’, NULL, ‘a@gmail.com’, 10, 1430560443, 1430560443);


— Indexes for dumped tables


— Indexes for table `user`

ALTER TABLE `user`
 ADD PRIMARY KEY (`id`);


— AUTO_INCREMENT for dumped tables


— AUTO_INCREMENT for table `user`

ALTER TABLE `user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1234;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
[/sourcecode]

Klik “go”.

Di folder controllers, kita buat file UserController.php seperti ini :

[sourcecode language=”html”]<?php

namespace app\controllers;

use Yii;
use app\models\User;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
* UserController implements the CRUD actions for User model.
*/
class UserController extends Controller
{
public function behaviors()
{
return [
‘verbs’ => [
‘class’ => VerbFilter::className(),
‘actions’ => [
‘delete’ => [‘post’],
],
],
];
}

/**
* Lists all User models.
* @return mixed
*/
public function actionIndex()
{
$dataProvider = new ActiveDataProvider([
‘query’ => User::find(),
‘pagination’ => array(‘pageSize’ => 39),
]);

return $this->render(‘index’, [
‘dataProvider’ => $dataProvider,
]);
}

/**
* Displays a single User model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render(‘view’, [
‘model’ => $this->findModel($id),
]);
}

/**
* Creates a new User model.
* If creation is successful, the browser will be redirected to the ‘view’ page.
* @return mixed
*/
public function actionCreate()
{
$model = new User();

if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect([‘view’, ‘id’ => $model->id]);
} else {
return $this->render(‘create’, [
‘model’ => $model,
]);
}

}

/**
* Updates an existing User model.
* If update is successful, the browser will be redirected to the ‘view’ page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);

if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect([‘view’, ‘id’ => $model->id]);
} else {
return $this->render(‘update’, [
‘model’ => $model,
]);
}
}

/**
* Deletes an existing User model.
* If deletion is successful, the browser will be redirected to the ‘index’ page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();

return $this->redirect([‘index’]);
}

/**
* Finds the User model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return User the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = User::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(‘The requested page does not exist.’);
}
}
}[/sourcecode]

Selanjutnya, di folder models, pada file User.php silahkan edit, dengan cara, hapus semua isinya dengan cara Ctrl + a delete, ganti semua isinya dengan code di bawah ini.

[sourcecode language=”html”]<?php

namespace app\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;

/**
* @inheritdoc
*/
public static function tableName()
{
return ‘{{%user}}’;
}
public function getNamaSkpd()
{
return $this->hasOne(Skpd::className(), [‘id_skpd’ => ‘id_skpd’]);
}
public function getNamaBagian()
{
return $this->hasOne(Bagian::className(), [‘id_bagian’ => ‘id_bagian’]);
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[‘status’, ‘default’, ‘value’ => self::STATUS_ACTIVE],
[‘status’, ‘in’, ‘range’ => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}

/**
* @inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne([‘id’ => $id, ‘status’ => self::STATUS_ACTIVE]);
}

/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException(‘"findIdentityByAccessToken" is not implemented.’);
}

/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
return static::findOne([‘username’ => $username, ‘status’ => self::STATUS_ACTIVE]);
}

/**
* Finds user by password reset token
*
* @param string $token password reset token
* @return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}

return static::findOne([
‘password_reset_token’ => $token,
‘status’ => self::STATUS_ACTIVE,
]);
}

/**
* Finds out if password reset token is valid
*
* @param string $token password reset token
* @return boolean
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$expire = Yii::$app->params[‘user.passwordResetTokenExpire’];
$parts = explode(‘_’, $token);
$timestamp = (int) end($parts);
return $timestamp + $expire >= time();
}

/**
* @inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}

/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}

/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}

/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}

/**
* Generates password hash from password and sets it to the model
*
* @param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}

/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}

/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . ‘_’ . time();
}

/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
}[/sourcecode]

Selesai sudah kita buat login dengan menggunakan database.

Selanjutnya test dengan melakukan login dengan username : demo dan password : 123456

Masih semangat!!! ayo kita lanjutkan …..

Tutorial selanjutnya silahkan KLIK DISINI

Leave a Reply

Your email address will not be published. Required fields are marked *

*