Commit 9d9cbed1 authored by achilleas's avatar achilleas

add oauthost iek_users

parent acca5b3a
{
"name": "drupal/iek",
"type": "drupal-module",
"description": "IEK Registration",
"keywords": ["Drupal"],
"license": "GPL-2.0+",
"homepage": "https://www.drupal.org/project/iek",
"minimum-stability": "dev",
"support": {
"issues": "https://www.drupal.org/project/issues/iek",
"source": "http://cgit.drupalcode.org/iek"
},
"require": { }
}
name: iek
type: module
description: IEK user table
core: 8.x
package: IEK
dependencies:
entity.iek_users.add_form:
route_name: entity.iek_users.add_form
title: 'Add Iek users'
appears_on:
- entity.iek_users.collection
# Iek users menu items definition
entity.iek_users.collection:
title: 'Iek users list'
route_name: entity.iek_users.collection
description: 'List Iek users entities'
parent: system.admin_structure
weight: 100
iek_users.admin.structure.settings:
title: Iek users settings
description: 'Configure Iek users entities'
route_name: iek_users.settings
parent: system.admin_structure
# Iek users routing definition
iek_users.settings_tab:
route_name: iek_users.settings
title: 'Settings'
base_route: iek_users.settings
entity.iek_users.canonical:
route_name: entity.iek_users.canonical
base_route: entity.iek_users.canonical
title: 'View'
entity.iek_users.edit_form:
route_name: entity.iek_users.edit_form
base_route: entity.iek_users.canonical
title: 'Edit'
entity.iek_users.delete_form:
route_name: entity.iek_users.delete_form
base_route: entity.iek_users.canonical
title: Delete
weight: 10
<?php
/**
* @file
* Contains iek.module.
*/
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*/
function iek_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
// Main module help for the iek module.
case 'help.page.iek':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('IEK Registration') . '</p>';
return $output;
default:
}
}
/**
* Implements hook_theme().
*/
function iek_theme() {
return [
'iek' => [
'template' => 'iek',
'render element' => 'children',
],
];
}
function iek_mail($key, &$message, $params) {
$options = array(
'langcode' => $message['langcode'],
);
switch ($key) {
case 'send_verification_code':
$message['from'] = \Drupal::config('system.site')->get('mail');
$message['subject'] = t('Email Confirmation Needed', $options);
$message['body'][] = $params['message'];
break;
}
}
add iek users entities:
title: 'Create new Iek users entities'
administer iek users entities:
title: 'Administer Iek users entities'
description: 'Allow to access the administration form to configure Iek users entities.'
restrict access: true
delete iek users entities:
title: 'Delete Iek users entities'
edit iek users entities:
title: 'Edit Iek users entities'
access iek users overview:
title: 'Access the Iek users overview page'
view published iek users entities:
title: 'View published Iek users entities'
view unpublished iek users entities:
title: 'View unpublished Iek users entities'
eiek.user.send_verification_code:
path: '/eiek/user/sendvercode'
options:
_auth: [ 'basic_auth' ]
defaults:
_controller: '\Drupal\iek\Controller\CurrentUser::sendVerificationCode'
requirements:
_user_is_logged_in: 'TRUE'
eiek.user.verify_verification_code:
path: '/eiek/user/verifyvercode'
options:
_auth: [ 'basic_auth' ]
defaults:
_controller: '\Drupal\iek\Controller\CurrentUser::verifyVerificationCode'
requirements:
_user_is_logged_in: 'TRUE'
eiek.user.save_profile:
path: '/eiek/user/save'
options:
_auth: [ 'basic_auth' ]
defaults:
_controller: '\Drupal\iek\Controller\CurrentUser::saveUserProfile'
requirements:
_user_is_logged_in: 'TRUE'
eiek.user.get_data:
path: '/eiek/userdata'
options:
_auth: [ 'basic_auth' ]
defaults:
_controller: '\Drupal\iek\Controller\CurrentUser::getEiekUserData'
requirements:
_user_is_logged_in: 'TRUE'
eiek.current_user:
path: '/eiek/curuser'
options:
_auth: [ 'basic_auth' ]
defaults:
_controller: '\Drupal\iek\Controller\CurrentUser::getLoginInfo'
requirements:
_user_is_logged_in: 'TRUE'
services:
logger.channel.oauth:
parent: 'logger.channel_base'
arguments: ['oauthost']
<?php
/**
* @file
* Contains iek_users.page.inc.
*
* Page callback for Iek users entities.
*/
use Drupal\Core\Render\Element;
/**
* Prepares variables for Iek users templates.
*
* Default template: iek_users.html.twig.
*
* @param array $variables
* An associative array containing:
* - elements: An associative array containing the user information and any
* - attributes: HTML attributes for the containing element.
*/
function template_preprocess_iek_users(array &$variables) {
// Fetch IekUsers Entity Object.
$iek_users = $variables['elements']['#iek_users'];
// Helpful $content variable for templates.
foreach (Element::children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
}
<?php
namespace Drupal\iek\Controller;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Database\Connection;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
class CurrentUser extends ControllerBase
{
protected $entityTypeManager;
protected $logger;
protected $connection;
public function __construct(
EntityTypeManagerInterface $entityTypeManager,
Connection $connection,
LoggerChannelFactoryInterface $loggerChannel
)
{
$this->entityTypeManager = $entityTypeManager;
$this->connection = $connection;
$this->logger = $loggerChannel->get('eiek');
}
public static function create(ContainerInterface $container)
{
return new static(
$container->get('entity_type.manager'),
$container->get('database'),
$container->get('logger.factory')
);
}
public function getLoginInfo(Request $request)
{
$authToken = $request->headers->get('PHP_AUTH_USER');
$eiekUsers = $this->entityTypeManager->getStorage('iek_users')->loadByProperties(array('authtoken' => $authToken));
$eiekUser = reset($eiekUsers);
if ($eiekUser) {
return $this->respondWithStatus([
'name' => $eiekUser->name->value,
], Response::HTTP_OK);
} else {
return $this->respondWithStatus([
'message' => t("EIEK user not found"),
], Response::HTTP_FORBIDDEN);
}
}
public function getEiekUserData(Request $request)
{
$authToken = $request->headers->get('PHP_AUTH_USER');
$eiekUsers = $this->entityTypeManager->getStorage('iek_users')->loadByProperties(array('authtoken' => $authToken));
$eiekUser = reset($eiekUsers);
if ($eiekUser) {
$user = $this->entityTypeManager->getStorage('user')->load($eiekUser->user_id->target_id);
if ($user) {
$userName = $eiekUser->name->value;
$userEmail = $user->mail->value;
return $this->respondWithStatus([
'userName' => mb_substr($eiekUser->name->value,0,4,'UTF-8') !== "####" ? $eiekUser->name->value : '',
'userEmail' => mb_substr($user->mail->value,0,4,'UTF-8') !== "####" ? $user->mail->value : '',
'verificationCodeVerified' => $eiekUser->verificationcodeverified->value,
], Response::HTTP_OK);
} else {
return $this->respondWithStatus([
'message' => t("user not found"),
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
} else {
return $this->respondWithStatus([
'message' => t("EIEK user not found"),
], Response::HTTP_FORBIDDEN);
}
}
public function sendVerificationCode(Request $request)
{
if (!$request->isMethod('POST')) {
return $this->respondWithStatus([
"message" => t("Method Not Allowed")
], Response::HTTP_METHOD_NOT_ALLOWED);
}
$authToken = $request->headers->get('PHP_AUTH_USER');
$trx = $this->connection->startTransaction();
try {
$eiekUsers = $this->entityTypeManager->getStorage('iek_users')->loadByProperties(array('authtoken' => $authToken));
$eiekUser = reset($eiekUsers);
if ($eiekUser) {
$user = $this->entityTypeManager->getStorage('user')->load($eiekUser->user_id->target_id);
if ($user) {
$postData = null;
if ($content = $request->getContent()) {
$postData = json_decode($content);
$verificationCode = uniqid();
$eiekUser->set('verificationcode', $verificationCode);
$eiekUser->set('verificationcodeverified', FALSE);
$eiekUser->save();
$user->set('mail', $postData->userEmail);
$user->save();
$this->sendEmailWithVerificationCode($postData->userEmail, $verificationCode, $user);
return $this->respondWithStatus([
'userEmail' => $postData->userEmail,
'verCode' => $verificationCode,
], Response::HTTP_OK);
}
else {
return $this->respondWithStatus([
'message' => t("post with no data"),
], Response::HTTP_BAD_REQUEST);
}
} else {
return $this->respondWithStatus([
'message' => t("user not found"),
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
} else {
return $this->respondWithStatus([
'message' => t("EIEK user not found"),
], Response::HTTP_FORBIDDEN);
}
} catch (\Exception $ee) {
$this->logger->warning($ee->getMessage());
$trx->rollback();
return false;
}
}
private function sendEmailWithVerificationCode($email, $vc, $user) {
$mailManager = \Drupal::service('plugin.manager.mail');
$module = 'eiek';
$key = 'send_verification_code';
$to = $email;
$params['message'] = 'verification code=' . $vc;
$langcode = $user->getPreferredLangcode();
$send = true;
$mail_sent = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
if ($mail_sent) {
$this->logger->info("Mail Sent successfully.");
}
else {
$this->logger->info("There is error in sending mail.");
}
return;
}
public function verifyVerificationCode(Request $request)
{
if (!$request->isMethod('POST')) {
return $this->respondWithStatus([
"message" => t("Method Not Allowed")
], Response::HTTP_METHOD_NOT_ALLOWED);
}
$authToken = $request->headers->get('PHP_AUTH_USER');
$eiekUsers = $this->entityTypeManager->getStorage('iek_users')->loadByProperties(array('authtoken' => $authToken));
$eiekUser = reset($eiekUsers);
if ($eiekUser) {
$user = $this->entityTypeManager->getStorage('user')->load($eiekUser->user_id->target_id);
if ($user) {
$postData = null;
if ($content = $request->getContent()) {
$postData = json_decode($content);
if ($eiekUser->verificationcode->value !== $postData->verificationCode) {
return $this->respondWithStatus([
'userEmail' => $user->mail->value,
'verificationCodeVerified' => false
], Response::HTTP_OK);
} else {
$eiekUser->set('verificationcodeverified', true);
$eiekUser->save();
return $this->respondWithStatus([
'userEmail' => $user->mail->value,
'verificationCodeVerified' => true
], Response::HTTP_OK);
}
}
} else {
return $this->respondWithStatus([
'message' => t("user not found"),
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
} else {
return $this->respondWithStatus([
'message' => t("EIEK user not found"),
], Response::HTTP_FORBIDDEN);
}
}
public function saveUserProfile(Request $request)
{
if (!$request->isMethod('POST')) {
return $this->respondWithStatus([
"message" => t("Method Not Allowed")
], Response::HTTP_METHOD_NOT_ALLOWED);
}
$authToken = $request->headers->get('PHP_AUTH_USER');
$eiekUsers = $this->entityTypeManager->getStorage('iek_users')->loadByProperties(array('authtoken' => $authToken));
$eiekUser = reset($eiekUsers);
if ($eiekUser) {
$postData = null;
if ($content = $request->getContent()) {
$postData = json_decode($content);
$eiekUser->set('name', $postData->userProfile->userName);
$eiekUser->save();
return $this->respondWithStatus([
'message' => t("profile saved"),
], Response::HTTP_OK);
} else {
return $this->respondWithStatus([
'message' => t("post with no data"),
], Response::HTTP_BAD_REQUEST);
}
} else {
return $this->respondWithStatus([
'message' => t("EIEK user not found"),
], Response::HTTP_FORBIDDEN);
}
}
private function respondWithStatus($arr, $s) {
$res = new JsonResponse($arr);
$res->setStatusCode($s);
return $res;
}
}
<?php
namespace Drupal\iek\Entity;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\user\UserInterface;
/**
* Defines the Iek users entity.
*
* @ingroup iek
*
* @ContentEntityType(
* id = "iek_users",
* label = @Translation("Iek users"),
* handlers = {
* "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
* "list_builder" = "Drupal\iek\IekUsersListBuilder",
* "views_data" = "Drupal\iek\Entity\IekUsersViewsData",
*
* "form" = {
* "default" = "Drupal\iek\Form\IekUsersForm",
* "add" = "Drupal\iek\Form\IekUsersForm",
* "edit" = "Drupal\iek\Form\IekUsersForm",
* "delete" = "Drupal\iek\Form\IekUsersDeleteForm",
* },
* "access" = "Drupal\iek\IekUsersAccessControlHandler",
* "route_provider" = {
* "html" = "Drupal\iek\IekUsersHtmlRouteProvider",
* },
* },
* base_table = "iek_users",
* admin_permission = "administer iek users entities",
* entity_keys = {
* "id" = "id",
* "label" = "name",
* "uuid" = "uuid",
* "uid" = "user_id",
* "langcode" = "langcode",
* "status" = "status",
* "drupaluser_id" = "drupaluser_id",
* "name" = "name",
* "taxis_taxid" = "taxis_taxid",
* "requesttoken" = "requesttoken",
* "accesstoken" = "accesstoken",
* "authtoken" = "authtoken",
* },
* links = {
* "canonical" = "/admin/structure/iek_users/{iek_users}",
* "add-form" = "/admin/structure/iek_users/add",
* "edit-form" = "/admin/structure/iek_users/{iek_users}/edit",
* "delete-form" = "/admin/structure/iek_users/{iek_users}/delete",
* "collection" = "/admin/structure/iek_users",
* },
* field_ui_base_route = "iek_users.settings"
* )
*/
class IekUsers extends ContentEntityBase implements IekUsersInterface {
use EntityChangedTrait;
/**
* {@inheritdoc}
*/
public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
parent::preCreate($storage_controller, $values);
$values += array(
'user_id' => \Drupal::currentUser()->id(),
);
}
/**
* {@inheritdoc}
*/
public function getName() {
return $this->get('name')->value;
}
/**
* {@inheritdoc}
*/
public function setName($name) {
$this->set('name', $name);
return $this;
}