1: <?php
2: 3: 4: 5: 6: 7: 8: 9:
10:
11: namespace Kotchasan;
12:
13: use Kotchasan\Http\Request;
14:
15: 16: 17: 18: 19: 20: 21:
22: class ApiController extends KBase
23: {
24: 25: 26: 27: 28: 29: 30:
31: public function index(Request $request)
32: {
33: if (empty(self::$cfg->api_token) || empty(self::$cfg->api_ips)) {
34:
35: $result = array(
36: 'code' => 503,
37: 'message' => 'Unavailable API',
38: );
39: } elseif (in_array('0.0.0.0', self::$cfg->api_ips) || in_array($request->getClientIp(), self::$cfg->api_ips)) {
40: try {
41:
42: $module = $request->get('module')->filter('a-z0-9');
43: $method = $request->get('method')->filter('a-z');
44: $action = $request->get('action')->filter('a-z');
45:
46:
47: $className = ucfirst($module).'\\'.ucfirst($method).'\\Model';
48:
49: if (method_exists($className, $action)) {
50:
51: $result = createClass($className)->$action($request);
52: } else {
53:
54: $result = array(
55: 'code' => 404,
56: 'message' => 'Object Not Found',
57: );
58: }
59: } catch (ApiException $e) {
60:
61: $result = array(
62: 'code' => $e->getCode(),
63: 'message' => $e->getMessage(),
64: );
65: }
66: } else {
67:
68: $result = array(
69: 'code' => 403,
70: 'message' => 'Forbidden',
71: );
72: }
73:
74: $response = new \Kotchasan\Http\Response();
75: $response->withHeaders(array(
76: 'Content-type' => 'application/json; charset=UTF-8',
77: ))
78: ->withStatus(empty($result['code']) ? 200 : $result['code'])
79: ->withContent(json_encode($result))
80: ->send();
81: }
82:
83: 84: 85: 86: 87: 88: 89: 90: 91:
92: public static function validateToken($token)
93: {
94: if (self::$cfg->api_token === $token) {
95: return true;
96: }
97: throw new ApiException('Invalid token', 401);
98: }
99:
100: 101: 102: 103: 104: 105: 106: 107: 108:
109: public static function validateTokenBearer(Request $request)
110: {
111: if (preg_match('/^Bearer\s'.self::$cfg->api_token.'$/', $request->getHeaderLine('Authorization'))) {
112: return true;
113: }
114: throw new ApiException('Invalid token', 401);
115: }
116:
117: 118: 119: 120: 121: 122: 123: 124: 125:
126: public static function validateSign($params)
127: {
128: if (count($params) > 1 && isset($params['sign'])) {
129: $sign = $params['sign'];
130: unset($params['sign']);
131: if ($sign === \Kotchasan\Password::generateSign($params, self::$cfg->api_secret)) {
132: return true;
133: }
134: }
135: throw new ApiException('Invalid sign', 403);
136:
137: }
138:
139: 140: 141: 142: 143: 144: 145: 146: 147: 148:
149: public static function validateMethod(Request $request, $method)
150: {
151: if ($request->getMethod() === $method) {
152: return true;
153: }
154: throw new ApiException('Method not allowed', 405);
155: }
156: }
157: