Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php defined('BASEPATH') OR exit('No direct script access allowed');
- Class Api extends CI_Controller
- {
- public function __construct()
- {
- parent::__construct();
- $this->load->model('api_model','api');
- header("Access-Control-Allow-Origin: *");
- header("Access-Control-Allow-Methods: GET, OPTIONS");
- header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
- if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
- die();
- }
- }
- public function login()
- {
- $this->form_validation->set_rules('username', 'Username', 'required');
- $this->form_validation->set_rules('password', 'Password', 'required');
- if($this->form_validation->run() == FALSE)
- {
- $output['errors'] = $this->form_validation->error_array();
- } else {
- $username = $this->input->post('username');
- $password = $this->input->post('password');
- $userdata = $this->api->authenticate($username, $password);
- $id = $userdata['user_id'];
- $token = $userdata['token'];
- if($id != false) {
- if(! isset($token)) {
- $key = base64_encode('add some randome key here');
- $payload = array(
- "iss" => "Add website address here",
- "iat" => time(),
- "exp" => time() + (3600 * 24 * 15),
- "context" => [
- "user" => [
- "username" => $username,
- "user_id" => $id
- ]
- ]
- );
- $jwt = JWT::encode($payload, $key);
- $this->db->insert('daktari_tokens', array(
- 'user_id'=>$id,
- 'value'=>$jwt,
- 'date_created'=>$payload['iat'],
- 'date_expiration'=>$payload['exp']));
- $output['errors'] = "";
- $output['token'] = $jwt;
- $output['user_id'] = $id;
- } else {
- $output['errors'] = "";
- $output['token'] = $token;
- $output['user_id'] = $id;
- }
- } else {
- $output['errors'] = 'User does not exist';
- }
- }
- echo json_encode($output);
- }
- public function register()
- {
- $this->form_validation->set_rules('firstname', 'Firstname', 'required');
- $this->form_validation->set_rules('lastname', 'Lastname', 'required');
- $this->form_validation->set_rules('username','Username','required|is_unique[daktari_users.username]', array(
- 'required' => 'You have not provided %s.',
- 'is_unique' => 'This %s already exists.'
- ));
- $this->form_validation->set_rules('password','Password','required|min_length[8]|max_length[64]');
- if($this->form_validation->run() == FALSE)
- {
- $message = $this->form_validation->error_array();
- echo json_encode($message);
- } else {
- if($this->api->create_user())
- {
- $output['errors'] = 'Account successfully created';
- } else {
- // echo json_encode('Unable to create account');
- $output['errors'] = 'Unable to create account';
- }
- echo json_encode($output);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement