Generate SMS token for systems handling authentication task of user management
outside of multiotp infrastructure
Cyril Ogana <cogana@gmail.com>
2015-07-25

@param string user - The username

@return int
@access public
178960
public function GenerateSmsToken($user = '') {
        $userName = $user;
        $nowEpoch = time();
        $smsNowSteps = $nowEpoch;
        $smsDigits = 6;
        $userTokenSeed = substr(md5(date("YmdHis").mt_rand(100000,999999)),0,20).substr(md5(mt_rand(100000,999999).date("YmdHis")),0,20);
        $smsSeedBin = hex2bin(md5('sMs'.$this->GetEncryptionKey().$userTokenSeed.$userName.$nowEpoch));
        $smsToken = $this->GenerateOathHotp($smsSeedBin,$smsNowSteps,$smsDigits);
        $smsNiceToken = $this->ConvertToNiceToken($smsToken);
        return $smsNiceToken;
    }
123940
public static function generateToken($userName, $keyString) {
        $userNameCast = (string) $userName;
        $keyStringCast = (string) $keyString;
        $multiOtpObj = new MultiotpWrapper($keyStringCast);
        return $multiOtpObj->GenerateSmsToken($userNameCast);
    }
300638
public function getUserToken(string $userName) : string {
        if (isset($this->userToken[$userName])) {
            return $this->userToken[$userName];
        }
    }
383262
public function send(NumberAwareInterface $user): void
    {
        $token = $this->pinGenerator->generate();
        $user->setPhoneNumberVerificationToken($token);
        $user->setPhoneNumberRequestedAt(new \DateTime());

        if (!$this->disabled) {
            $this->smsSender->send($user->getPhoneNumber(), 'Your token is: ' . $token);
        }
    }
470705
public static function login($user)
  {
    $token = $user->{config('auth.provider.' . Auth::$provider . '.with')} = Hash::random(70);
    $user->save();

    return Remember::login($token);
  }
4914
public function logUser(User $user)
    {
        $this->strictEventDispatcher->dispatch('log', 'Log\LogUserLogin', array($user));
        $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
        $this->container->get('security.token_storage')->setToken($token);
    }
808061
public UserAccessToken generateAccessToken(User user, String device) {
		if (user == null)
			return null;
		Criteria criteria = this.dao.newCriteria(UserAccessToken.class)
				.add(Restrictions.eq("user", user))
				.add(Restrictions.eqOrIsNull("device", device))
				.add(Restrictions.gt("expiration", new Date()))
				.addOrder(Order.asc("expiration"));
		List<UserAccessToken> tokens = this.dao.findByCriteria(criteria, UserAccessToken.class);
		if (GeneralUtils.isEmpty(tokens)) {
			UserAccessToken token = new UserAccessToken();
			token.setUser(user);
			token.setDevice(device);
			token.setCreation(new Date());
			token.setCreationIp(this.request.getRemoteAddr());
			token.setExpiration(new Date(token.getCreation().getTime() + token.getTtl()));
			token.setToken(CryptManager.digest(user.getEmail() + "#" + String.valueOf(token.getCreation().getTime())
					+ "@" + String.valueOf(Math.random())));
			this.dao.persist(token);
			return token;
		}
		return tokens.get(0);
	}
510155
public function currentUser()
    {
        try {
            if (!array_key_exists('tokenstorage',$_SESSION)) {
                throw new \Exception('Token storage not found.');
            }
            $storage = $_SESSION['tokenstorage'];
            $username = $storage->getToken()->getUsername();
            // echo print_r($storage->getToken()->getId(), true);
            $users = $this->erdikoUser->getByParams(['email' => $username]);
            if (!count($users)) {
                throw new \Exception('User not found.');
            }
            $user = $users[0];
        } catch (\Exception $e) {
            $user = $this->erdikoUser->getGeneral();
        }
        return $user;
    }
852257
public static function credentialsGrant($user) {  
        $config = require(Dir::config());
        $auth = $config['auth']; 
        $time = time();
        $token = [
            'iat' => $time, 
            'exp' => $time + (60*60), 
            'data' => [ 
                'user' => $user
            ]
        ];
        
        return JWT::encode($token, $auth['key']);     
    }
478739
protected function generateToken(SubjectContract $user)
    {
        $tokenGenerator = $this->getGenerator();
        $claims = $user->getJWTClaims();
        $claims['sub'] = $user->getJWTSubject();
        $claims[static::JWT_GUARD_CLAIM] = $this->id;
        if (!($token = $tokenGenerator($claims))) {
            throw new InvalidTokenException("Unable to generate token");
        }
        return $token;
    }
479434
public function countUnread(User $user)
    {
        return $this->createQueryBuilder('m')
            ->select('count(m)')
            ->join('m.userMessages', 'um')
            ->where('m.user != :sender')
            ->orWhere('m.user IS NULL')
            ->andWhere('um.user = :user')
            ->andWhere('um.isRead = 0')
            ->andWhere('um.isRemoved = 0')
            ->setParameter(':user', $user)
            ->setParameter(':sender', $user)
            ->getQuery()
            ->getSingleScalarResult();
    }
358994
public function generateToken()
    {
        $adminUser = $this->auth->getUser();
        $refreshToken = $adminUser->getRefreshToken();

        if ($refreshToken) {
            $accessToken = $this->client->getAccessToken(
                $this->configFactory->getTokenUrl(),
                $this->buildUrlParams(
                    $this->helper->encryptor->decrypt($refreshToken)
                )
            );

            if (is_string($accessToken)) {
                return $accessToken;
            }
        }

        return false;
    }
1193253
final public static function createOtpToken (string $username)
	{
		$token = self::setOtpToken();
		return self::setUserOtpToken($username, $token);
	}
557283
protected function getUserByToken()
    {
        // Look up in cache and return if found
        if ($user = cache_get('api.userToken', $this->getCacheParams())) {
            return $user;
        }

        // Look up in database
        $user = $this->generateQuery()->first();

        // Add to cache
       if ($user) {
           cache_put('api.userToken', $this->getCacheParams(), $user);
       }

        return $user;
    }
1041244
public function lookupNorthstarUser($user)
  {
    $northstarAPIConfig = $this->mbConfig->getProperty('northstar_config');
    if (empty($northstarAPIConfig['host'])) {
      throw new Exception('MB_Toolbox->lookupNorthstarUser() northstar_config missing host setting.');
    }

    $northstarUrl =  $northstarAPIConfig['host'];

    // Append port if exists.
    if (!empty($northstarAPIConfig['port'])) {
      $port = (int) $northstarAPIConfig['port'];
      // Port is within allowed range:
      // https://en.wikipedia.org/wiki/Port_(computer_networking)#Details
      if ($port > 0 && $port < 65536) {
        $northstarUrl .= ':' . $port;
      }
    }

    // Api version.
    $northstarUrl .= '/' . self::NORTHSTAR_API_VERSION . '/';

    // Lookup by email.
    if (!empty($user->email)) {
      $endpoint = $northstarUrl . 'users/email/' . $user->email;
      $result = $this->mbToolboxcURL->curlGet($endpoint);

      try {
        $northstarUser = $this->parseNorthstarUserResponse($result);
        echo '- User loaded from Northstar by email: '
          . $user->email . PHP_EOL;
        return $northstarUser;
      } catch (Exception $e) {
        echo '- Coundn\'t load user from Northstar by email: '
          . $user->email . PHP_EOL;
      }
    }

    // Lookup by phone.
    if (!empty($user->mobile)) {
      $endpoint = $northstarUrl . 'users/mobile/' . $user->mobile;
      $result = $this->mbToolboxcURL->curlGet($endpoint);

      try {
        $northstarUser = $this->parseNorthstarUserResponse($result);
        echo '- User loaded from Northstar by mobile: '
          . $user->mobile . PHP_EOL;
        return $northstarUser;
      } catch (Exception $e) {
        echo '- Coundn\'t load user from Northstar by mobile: '
          . $user->mobile . PHP_EOL;
      }
    }

    return false;
  }
1245283
public function getUserId() {
    if (array_key_exists(self::USER_ATTR, $this->payload)) {
      return $this->payload[self::USER_ATTR];
    }
    throw new AuthException("No user_id in token");
  }
1205127
public function getTotal($user)
    {
        $leaderboardType = $this->getLeaderboardTypeService()->getLeaderboardTypeDefault();
        $leaderboardUser = $this->getLeaderboardMapper()->findOneBy(
            array(
                'user' => $user,
                'leaderboardType' => $leaderboardType
            )
        );
        if (!$leaderboardUser) {
            return 0;
        }
        return $leaderboardUser->getTotalPoints();
    }