Send and receive SMS messages using your Android phone programmatically via a simple HTTP API
Add page for managing phone API keys
Acho Arnoldf2e2d767fedc
diff --git a/api/docs/docs.go b/api/docs/docs.goindex 273b0eb5..dcedd506 100644--- a/api/docs/docs.go+++ b/api/docs/docs.go@@ -23,6 +23,286 @@ const docTemplate = `{"host": "{{.Host}}","basePath": "{{.BasePath}}","paths": {+ "/api-keys": {+ "get": {+ "security": [+ {+ "ApiKeyAuth": []+ }+ ],+ "description": "Get list phone API keys which a user has registered on the httpSMS application",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "PhoneAPIKeys"+ ],+ "summary": "Get the phone API keys of a user",+ "parameters": [+ {+ "minimum": 0,+ "type": "integer",+ "description": "number of heartbeats to skip",+ "name": "skip",+ "in": "query"+ },+ {+ "type": "string",+ "description": "filter api keys with name containing query",+ "name": "query",+ "in": "query"+ },+ {+ "maximum": 100,+ "minimum": 1,+ "type": "integer",+ "description": "number of phone api keys to return",+ "name": "limit",+ "in": "query"+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/responses.PhoneAPIKeysResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/responses.BadRequest"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/responses.Unauthorized"+ }+ },+ "422": {+ "description": "Unprocessable Entity",+ "schema": {+ "$ref": "#/definitions/responses.UnprocessableEntity"+ }+ },+ "500": {+ "description": "Internal Server Error",+ "schema": {+ "$ref": "#/definitions/responses.InternalServerError"+ }+ }+ }+ },+ "post": {+ "security": [+ {+ "ApiKeyAuth": []+ }+ ],+ "description": "Creates a new phone API key which can be used to log in to the httpSMS app on your Android phone",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "PhoneAPIKeys"+ ],+ "summary": "Store phone API key",+ "parameters": [+ {+ "description": "Payload of new phone API key.",+ "name": "payload",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/requests.PhoneAPIKeyStoreRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/responses.PhoneAPIKeyResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/responses.BadRequest"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/responses.Unauthorized"+ }+ },+ "422": {+ "description": "Unprocessable Entity",+ "schema": {+ "$ref": "#/definitions/responses.UnprocessableEntity"+ }+ },+ "500": {+ "description": "Internal Server Error",+ "schema": {+ "$ref": "#/definitions/responses.InternalServerError"+ }+ }+ }+ }+ },+ "/api-keys/{phoneAPIKeyID}": {+ "delete": {+ "security": [+ {+ "ApiKeyAuth": []+ }+ ],+ "description": "Delete a phone API Key from the database and cannot be used for authentication anymore.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "PhoneAPIKeys"+ ],+ "summary": "Delete a phone API key from the database.",+ "parameters": [+ {+ "type": "string",+ "default": "32343a19-da5e-4b1b-a767-3298a73703ca",+ "description": "ID of the phone API key",+ "name": "phoneAPIKeyID",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "204": {+ "description": "No Content",+ "schema": {+ "$ref": "#/definitions/responses.NoContent"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/responses.BadRequest"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/responses.Unauthorized"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/responses.NotFound"+ }+ },+ "422": {+ "description": "Unprocessable Entity",+ "schema": {+ "$ref": "#/definitions/responses.UnprocessableEntity"+ }+ },+ "500": {+ "description": "Internal Server Error",+ "schema": {+ "$ref": "#/definitions/responses.InternalServerError"+ }+ }+ }+ }+ },+ "/api-keys/{phoneAPIKeyID}/phones/{phoneID}": {+ "delete": {+ "security": [+ {+ "ApiKeyAuth": []+ }+ ],+ "description": "You will need to login again to the httpSMS app on your Android phone with a new phone API key.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "PhoneAPIKeys"+ ],+ "summary": "Remove the association of a phone from the phone API key.",+ "parameters": [+ {+ "type": "string",+ "default": "32343a19-da5e-4b1b-a767-3298a73703ca",+ "description": "ID of the phone API key",+ "name": "phoneAPIKeyID",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "default": "32343a19-da5e-4b1b-a767-3298a73703ca",+ "description": "ID of the phone",+ "name": "phoneID",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "204": {+ "description": "No Content",+ "schema": {+ "$ref": "#/definitions/responses.NoContent"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/responses.BadRequest"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/responses.Unauthorized"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/responses.NotFound"+ }+ },+ "422": {+ "description": "Unprocessable Entity",+ "schema": {+ "$ref": "#/definitions/responses.UnprocessableEntity"+ }+ },+ "500": {+ "description": "Internal Server Error",+ "schema": {+ "$ref": "#/definitions/responses.InternalServerError"+ }+ }+ }+ }+ },"/billing/usage": {"get": {"security": [@@ -1332,6 +1612,13 @@ const docTemplate = `{],"summary": "Search all messages of a user","parameters": [+ {+ "type": "string",+ "description": "Cloudflare turnstile token https://www.cloudflare.com/en-gb/application-services/products/turnstile/",+ "name": "token",+ "in": "header",+ "required": true+ },{"type": "string","default": "+18005550199,+18005550100",@@ -1740,6 +2027,69 @@ const docTemplate = `{}}},+ "/phones/fcm-token": {+ "put": {+ "security": [+ {+ "ApiKeyAuth": []+ }+ ],+ "description": "Updates the FCM token of a phone. If the phone with this number does not exist, a new one will be created. Think of this method like an 'upsert'",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "Phones"+ ],+ "summary": "Upserts the FCM token of a phone",+ "parameters": [+ {+ "description": "Payload of new FCM token.",+ "name": "payload",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/requests.PhoneFCMToken"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/responses.PhoneResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/responses.BadRequest"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/responses.Unauthorized"+ }+ },+ "422": {+ "description": "Unprocessable Entity",+ "schema": {+ "$ref": "#/definitions/responses.UnprocessableEntity"+ }+ },+ "500": {+ "description": "Internal Server Error",+ "schema": {+ "$ref": "#/definitions/responses.InternalServerError"+ }+ }+ }+ }+ },"/phones/{phoneID}": {"delete": {"security": [@@ -2858,6 +3208,70 @@ const docTemplate = `{}}},+ "entities.PhoneAPIKey": {+ "type": "object",+ "required": [+ "api_key",+ "created_at",+ "id",+ "name",+ "phone_ids",+ "phone_numbers",+ "updated_at",+ "user_email",+ "user_id"+ ],+ "properties": {+ "api_key": {+ "type": "string",+ "example": "pk_DGW8NwQp7mxKaSZ72Xq9v67SLqSbWQvckzzmK8D6rvd7NywSEkdMJtuxKyEkYnCY"+ },+ "created_at": {+ "type": "string",+ "example": "2022-06-05T14:26:02.302718+03:00"+ },+ "id": {+ "type": "string",+ "example": "32343a19-da5e-4b1b-a767-3298a73703cb"+ },+ "name": {+ "type": "string",+ "example": "Business Phone Key"+ },+ "phone_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "example": [+ "[32343a19-da5e-4b1b-a767-3298a73703cb",+ "32343a19-da5e-4b1b-a767-3298a73703cc]"+ ]+ },+ "phone_numbers": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "example": [+ "[+18005550199",+ "+18005550100]"+ ]+ },+ "updated_at": {+ "type": "string",+ "example": "2022-06-05T14:26:02.302718+03:00"+ },+ "user_email": {+ "type": "string",+ "example": "[email protected]"+ },+ "user_id": {+ "type": "string",+ "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC"+ }+ }+ },"entities.User": {"type": "object","required": [@@ -2868,6 +3282,7 @@ const docTemplate = `{"id","notification_heartbeat_enabled","notification_message_status_enabled",+ "notification_newsletter_enabled","notification_webhook_enabled","subscription_ends_at","subscription_id",@@ -2906,6 +3321,10 @@ const docTemplate = `{"type": "boolean","example": true},+ "notification_newsletter_enabled": {+ "type": "boolean",+ "example": true+ },"notification_webhook_enabled": {"type": "boolean","example": true@@ -3234,6 +3653,41 @@ const docTemplate = `{}}},+ "requests.PhoneAPIKeyStoreRequest": {+ "type": "object",+ "required": [+ "name"+ ],+ "properties": {+ "name": {+ "type": "string",+ "example": "My Phone API Key"+ }+ }+ },+ "requests.PhoneFCMToken": {+ "type": "object",+ "required": [+ "fcm_token",+ "phone_number",+ "sim"+ ],+ "properties": {+ "fcm_token": {+ "type": "string",+ "example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....."+ },+ "phone_number": {+ "type": "string",+ "example": "[+18005550199]"+ },+ "sim": {+ "description": "SIM is the SIM slot of the phone in case the phone has more than 1 SIM slot",+ "type": "string",+ "example": "SIM1"+ }+ }+ },"requests.PhoneUpsert": {"type": "object","required": [@@ -3284,6 +3738,7 @@ const docTemplate = `{"required": ["heartbeat_enabled","message_status_enabled",+ "newsletter_enabled","webhook_enabled"],"properties": {@@ -3295,6 +3750,10 @@ const docTemplate = `{"type": "boolean","example": true},+ "newsletter_enabled": {+ "type": "boolean",+ "example": true+ },"webhook_enabled": {"type": "boolean","example": true@@ -3682,6 +4141,51 @@ const docTemplate = `{}}},+ "responses.PhoneAPIKeyResponse": {+ "type": "object",+ "required": [+ "data",+ "message",+ "status"+ ],+ "properties": {+ "data": {+ "$ref": "#/definitions/entities.PhoneAPIKey"+ },+ "message": {+ "type": "string",+ "example": "item created successfully"+ },+ "status": {+ "type": "string",+ "example": "success"+ }+ }+ },+ "responses.PhoneAPIKeysResponse": {+ "type": "object",+ "required": [+ "data",+ "message",+ "status"+ ],+ "properties": {+ "data": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/entities.PhoneAPIKey"+ }+ },+ "message": {+ "type": "string",+ "example": "item created successfully"+ },+ "status": {+ "type": "string",+ "example": "success"+ }+ }+ },"responses.PhoneResponse": {"type": "object","required": [@@ -3858,7 +4362,7 @@ var SwaggerInfo = &swag.Spec{Host: "api.httpsms.com",BasePath: "/v1",Schemes: []string{"https"},- Title: "HTTP SMS API",+ Title: "httpSMS API Reference",Description: "API to send SMS messages using android [SmsManager](https://developer.android.com/reference/android/telephony/SmsManager) via HTTP",InfoInstanceName: "swagger",SwaggerTemplate: docTemplate,diff --git a/api/docs/swagger.json b/api/docs/swagger.jsonindex cd167e5a..07f074d2 100644--- a/api/docs/swagger.json+++ b/api/docs/swagger.json@@ -3,7 +3,7 @@"swagger": "2.0","info": {"description": "API to send SMS messages using android [SmsManager](https://developer.android.com/reference/android/telephony/SmsManager) via HTTP",- "title": "HTTP SMS API",+ "title": "httpSMS API Reference","contact": {"name": "HTTP SMS","email": "[email protected]"@@ -17,6 +17,262 @@"host": "api.httpsms.com","basePath": "/v1","paths": {+ "/api-keys": {+ "get": {+ "security": [+ {+ "ApiKeyAuth": []+ }+ ],+ "description": "Get list phone API keys which a user has registered on the httpSMS application",+ "consumes": ["application/json"],+ "produces": ["application/json"],+ "tags": ["PhoneAPIKeys"],+ "summary": "Get the phone API keys of a user",+ "parameters": [+ {+ "minimum": 0,+ "type": "integer",+ "description": "number of heartbeats to skip",+ "name": "skip",+ "in": "query"+ },+ {+ "type": "string",+ "description": "filter api keys with name containing query",+ "name": "query",+ "in": "query"+ },+ {+ "maximum": 100,+ "minimum": 1,+ "type": "integer",+ "description": "number of phone api keys to return",+ "name": "limit",+ "in": "query"+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/responses.PhoneAPIKeysResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/responses.BadRequest"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/responses.Unauthorized"+ }+ },+ "422": {+ "description": "Unprocessable Entity",+ "schema": {+ "$ref": "#/definitions/responses.UnprocessableEntity"+ }+ },+ "500": {+ "description": "Internal Server Error",+ "schema": {+ "$ref": "#/definitions/responses.InternalServerError"+ }+ }+ }+ },+ "post": {+ "security": [+ {+ "ApiKeyAuth": []+ }+ ],+ "description": "Creates a new phone API key which can be used to log in to the httpSMS app on your Android phone",+ "consumes": ["application/json"],+ "produces": ["application/json"],+ "tags": ["PhoneAPIKeys"],+ "summary": "Store phone API key",+ "parameters": [+ {+ "description": "Payload of new phone API key.",+ "name": "payload",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/requests.PhoneAPIKeyStoreRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/responses.PhoneAPIKeyResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/responses.BadRequest"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/responses.Unauthorized"+ }+ },+ "422": {+ "description": "Unprocessable Entity",+ "schema": {+ "$ref": "#/definitions/responses.UnprocessableEntity"+ }+ },+ "500": {+ "description": "Internal Server Error",+ "schema": {+ "$ref": "#/definitions/responses.InternalServerError"+ }+ }+ }+ }+ },+ "/api-keys/{phoneAPIKeyID}": {+ "delete": {+ "security": [+ {+ "ApiKeyAuth": []+ }+ ],+ "description": "Delete a phone API Key from the database and cannot be used for authentication anymore.",+ "consumes": ["application/json"],+ "produces": ["application/json"],+ "tags": ["PhoneAPIKeys"],+ "summary": "Delete a phone API key from the database.",+ "parameters": [+ {+ "type": "string",+ "default": "32343a19-da5e-4b1b-a767-3298a73703ca",+ "description": "ID of the phone API key",+ "name": "phoneAPIKeyID",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "204": {+ "description": "No Content",+ "schema": {+ "$ref": "#/definitions/responses.NoContent"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/responses.BadRequest"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/responses.Unauthorized"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/responses.NotFound"+ }+ },+ "422": {+ "description": "Unprocessable Entity",+ "schema": {+ "$ref": "#/definitions/responses.UnprocessableEntity"+ }+ },+ "500": {+ "description": "Internal Server Error",+ "schema": {+ "$ref": "#/definitions/responses.InternalServerError"+ }+ }+ }+ }+ },+ "/api-keys/{phoneAPIKeyID}/phones/{phoneID}": {+ "delete": {+ "security": [+ {+ "ApiKeyAuth": []+ }+ ],+ "description": "You will need to login again to the httpSMS app on your Android phone with a new phone API key.",+ "consumes": ["application/json"],+ "produces": ["application/json"],+ "tags": ["PhoneAPIKeys"],+ "summary": "Remove the association of a phone from the phone API key.",+ "parameters": [+ {+ "type": "string",+ "default": "32343a19-da5e-4b1b-a767-3298a73703ca",+ "description": "ID of the phone API key",+ "name": "phoneAPIKeyID",+ "in": "path",+ "required": true+ },+ {+ "type": "string",+ "default": "32343a19-da5e-4b1b-a767-3298a73703ca",+ "description": "ID of the phone",+ "name": "phoneID",+ "in": "path",+ "required": true+ }+ ],+ "responses": {+ "204": {+ "description": "No Content",+ "schema": {+ "$ref": "#/definitions/responses.NoContent"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/responses.BadRequest"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/responses.Unauthorized"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/responses.NotFound"+ }+ },+ "422": {+ "description": "Unprocessable Entity",+ "schema": {+ "$ref": "#/definitions/responses.UnprocessableEntity"+ }+ },+ "500": {+ "description": "Internal Server Error",+ "schema": {+ "$ref": "#/definitions/responses.InternalServerError"+ }+ }+ }+ }+ },"/billing/usage": {"get": {"security": [@@ -1200,6 +1456,13 @@"tags": ["Messages"],"summary": "Search all messages of a user","parameters": [+ {+ "type": "string",+ "description": "Cloudflare turnstile token https://www.cloudflare.com/en-gb/application-services/products/turnstile/",+ "name": "token",+ "in": "header",+ "required": true+ },{"type": "string","default": "+18005550199,+18005550100",@@ -1578,6 +1841,63 @@}}},+ "/phones/fcm-token": {+ "put": {+ "security": [+ {+ "ApiKeyAuth": []+ }+ ],+ "description": "Updates the FCM token of a phone. If the phone with this number does not exist, a new one will be created. Think of this method like an 'upsert'",+ "consumes": ["application/json"],+ "produces": ["application/json"],+ "tags": ["Phones"],+ "summary": "Upserts the FCM token of a phone",+ "parameters": [+ {+ "description": "Payload of new FCM token.",+ "name": "payload",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/requests.PhoneFCMToken"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/responses.PhoneResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/responses.BadRequest"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/responses.Unauthorized"+ }+ },+ "422": {+ "description": "Unprocessable Entity",+ "schema": {+ "$ref": "#/definitions/responses.UnprocessableEntity"+ }+ },+ "500": {+ "description": "Internal Server Error",+ "schema": {+ "$ref": "#/definitions/responses.InternalServerError"+ }+ }+ }+ }+ },"/phones/{phoneID}": {"delete": {"security": [@@ -2628,6 +2948,67 @@}}},+ "entities.PhoneAPIKey": {+ "type": "object",+ "required": [+ "api_key",+ "created_at",+ "id",+ "name",+ "phone_ids",+ "phone_numbers",+ "updated_at",+ "user_email",+ "user_id"+ ],+ "properties": {+ "api_key": {+ "type": "string",+ "example": "pk_DGW8NwQp7mxKaSZ72Xq9v67SLqSbWQvckzzmK8D6rvd7NywSEkdMJtuxKyEkYnCY"+ },+ "created_at": {+ "type": "string",+ "example": "2022-06-05T14:26:02.302718+03:00"+ },+ "id": {+ "type": "string",+ "example": "32343a19-da5e-4b1b-a767-3298a73703cb"+ },+ "name": {+ "type": "string",+ "example": "Business Phone Key"+ },+ "phone_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "example": [+ "[32343a19-da5e-4b1b-a767-3298a73703cb",+ "32343a19-da5e-4b1b-a767-3298a73703cc]"+ ]+ },+ "phone_numbers": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "example": ["[+18005550199", "+18005550100]"]+ },+ "updated_at": {+ "type": "string",+ "example": "2022-06-05T14:26:02.302718+03:00"+ },+ "user_email": {+ "type": "string",+ "example": "[email protected]"+ },+ "user_id": {+ "type": "string",+ "example": "WB7DRDWrJZRGbYrv2CKGkqbzvqdC"+ }+ }+ },"entities.User": {"type": "object","required": [@@ -2638,6 +3019,7 @@"id","notification_heartbeat_enabled","notification_message_status_enabled",+ "notification_newsletter_enabled","notification_webhook_enabled","subscription_ends_at","subscription_id",@@ -2676,6 +3058,10 @@"type": "boolean","example": true},+ "notification_newsletter_enabled": {+ "type": "boolean",+ "example": true+ },"notification_webhook_enabled": {"type": "boolean","example": true@@ -2957,6 +3343,35 @@}}},+ "requests.PhoneAPIKeyStoreRequest": {+ "type": "object",+ "required": ["name"],+ "properties": {+ "name": {+ "type": "string",+ "example": "My Phone API Key"+ }+ }+ },+ "requests.PhoneFCMToken": {+ "type": "object",+ "required": ["fcm_token", "phone_number", "sim"],+ "properties": {+ "fcm_token": {+ "type": "string",+ "example": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....."+ },+ "phone_number": {+ "type": "string",+ "example": "[+18005550199]"+ },+ "sim": {+ "description": "SIM is the SIM slot of the phone in case the phone has more than 1 SIM slot",+ "type": "string",+ "example": "SIM1"+ }+ }+ },"requests.PhoneUpsert": {"type": "object","required": [@@ -3007,6 +3422,7 @@"required": ["heartbeat_enabled","message_status_enabled",+ "newsletter_enabled","webhook_enabled"],"properties": {@@ -3018,6 +3434,10 @@"type": "boolean","example": true},+ "newsletter_enabled": {+ "type": "boolean",+ "example": true+ },"webhook_enabled": {"type": "boolean","example": true@@ -3333,6 +3753,43 @@}}},+ "responses.PhoneAPIKeyResponse": {+ "type": "object",+ "required": ["data", "message", "status"],+ "properties": {+ "data": {+ "$ref": "#/definitions/entities.PhoneAPIKey"+ },+ "message": {+ "type": "string",+ "example": "item created successfully"+ },+ "status": {+ "type": "string",+ "example": "success"+ }+ }+ },+ "responses.PhoneAPIKeysResponse": {+ "type": "object",+ "required": ["data", "message", "status"],+ "properties": {+ "data": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/entities.PhoneAPIKey"+ }+ },+ "message": {+ "type": "string",+ "example": "item created successfully"+ },+ "status": {+ "type": "string",+ "example": "success"+ }+ }+ },"responses.PhoneResponse": {"type": "object","required": ["data", "message", "status"],diff --git a/api/docs/swagger.yaml b/api/docs/swagger.yamlindex 0b5db182..f9ddbfc7 100644--- a/api/docs/swagger.yaml+++ b/api/docs/swagger.yaml@@ -325,6 +325,54 @@ definitions:- updated_at- user_idtype: object+ entities.PhoneAPIKey:+ properties:+ api_key:+ example: pk_DGW8NwQp7mxKaSZ72Xq9v67SLqSbWQvckzzmK8D6rvd7NywSEkdMJtuxKyEkYnCY+ type: string+ created_at:+ example: "2022-06-05T14:26:02.302718+03:00"+ type: string+ id:+ example: 32343a19-da5e-4b1b-a767-3298a73703cb+ type: string+ name:+ example: Business Phone Key+ type: string+ phone_ids:+ example:+ - "[32343a19-da5e-4b1b-a767-3298a73703cb"+ - 32343a19-da5e-4b1b-a767-3298a73703cc]+ items:+ type: string+ type: array+ phone_numbers:+ example:+ - "[+18005550199"+ - +18005550100]+ items:+ type: string+ type: array+ updated_at:+ example: "2022-06-05T14:26:02.302718+03:00"+ type: string+ user_email:+ example: [email protected]+ type: string+ user_id:+ example: WB7DRDWrJZRGbYrv2CKGkqbzvqdC+ type: string+ required:+ - api_key+ - created_at+ - id+ - name+ - phone_ids+ - phone_numbers+ - updated_at+ - user_email+ - user_id+ type: objectentities.User:properties:active_phone_id:@@ -348,6 +396,9 @@ definitions:notification_message_status_enabled:example: truetype: boolean+ notification_newsletter_enabled:+ example: true+ type: booleannotification_webhook_enabled:example: truetype: boolean@@ -380,6 +431,7 @@ definitions:- id- notification_heartbeat_enabled- notification_message_status_enabled+ - notification_newsletter_enabled- notification_webhook_enabled- subscription_ends_at- subscription_id@@ -625,6 +677,33 @@ definitions:required:- is_archivedtype: object+ requests.PhoneAPIKeyStoreRequest:+ properties:+ name:+ example: My Phone API Key+ type: string+ required:+ - name+ type: object+ requests.PhoneFCMToken:+ properties:+ fcm_token:+ example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd.....+ type: string+ phone_number:+ example: "[+18005550199]"+ type: string+ sim:+ description:+ SIM is the SIM slot of the phone in case the phone has more than+ 1 SIM slot+ example: SIM1+ type: string+ required:+ - fcm_token+ - phone_number+ - sim+ type: objectrequests.PhoneUpsert:properties:fcm_token:@@ -674,12 +753,16 @@ definitions:message_status_enabled:example: truetype: boolean+ newsletter_enabled:+ example: true+ type: booleanwebhook_enabled:example: truetype: booleanrequired:- heartbeat_enabled- message_status_enabled+ - newsletter_enabled- webhook_enabledtype: objectrequests.UserUpdate:@@ -952,6 +1035,38 @@ definitions:- message- statustype: object+ responses.PhoneAPIKeyResponse:+ properties:+ data:+ $ref: "#/definitions/entities.PhoneAPIKey"+ message:+ example: item created successfully+ type: string+ status:+ example: success+ type: string+ required:+ - data+ - message+ - status+ type: object+ responses.PhoneAPIKeysResponse:+ properties:+ data:+ items:+ $ref: "#/definitions/entities.PhoneAPIKey"+ type: array+ message:+ example: item created successfully+ type: string+ status:+ example: success+ type: string+ required:+ - data+ - message+ - status+ type: objectresponses.PhoneResponse:properties:data:@@ -1077,9 +1192,199 @@ info:license:name: AGPL-3.0url: https://raw.githubusercontent.com/NdoleStudio/http-sms-manager/main/LICENSE- title: HTTP SMS API+ title: httpSMS API Referenceversion: "1.0"paths:+ /api-keys:+ get:+ consumes:+ - application/json+ description:+ Get list phone API keys which a user has registered on the httpSMS+ application+ parameters:+ - description: number of heartbeats to skip+ in: query+ minimum: 0+ name: skip+ type: integer+ - description: filter api keys with name containing query+ in: query+ name: query+ type: string+ - description: number of phone api keys to return+ in: query+ maximum: 100+ minimum: 1+ name: limit+ type: integer+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: "#/definitions/responses.PhoneAPIKeysResponse"+ "400":+ description: Bad Request+ schema:+ $ref: "#/definitions/responses.BadRequest"+ "401":+ description: Unauthorized+ schema:+ $ref: "#/definitions/responses.Unauthorized"+ "422":+ description: Unprocessable Entity+ schema:+ $ref: "#/definitions/responses.UnprocessableEntity"+ "500":+ description: Internal Server Error+ schema:+ $ref: "#/definitions/responses.InternalServerError"+ security:+ - ApiKeyAuth: []+ summary: Get the phone API keys of a user+ tags:+ - PhoneAPIKeys+ post:+ consumes:+ - application/json+ description:+ Creates a new phone API key which can be used to log in to the+ httpSMS app on your Android phone+ parameters:+ - description: Payload of new phone API key.+ in: body+ name: payload+ required: true+ schema:+ $ref: "#/definitions/requests.PhoneAPIKeyStoreRequest"+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: "#/definitions/responses.PhoneAPIKeyResponse"+ "400":+ description: Bad Request+ schema:+ $ref: "#/definitions/responses.BadRequest"+ "401":+ description: Unauthorized+ schema:+ $ref: "#/definitions/responses.Unauthorized"+ "422":+ description: Unprocessable Entity+ schema:+ $ref: "#/definitions/responses.UnprocessableEntity"+ "500":+ description: Internal Server Error+ schema:+ $ref: "#/definitions/responses.InternalServerError"+ security:+ - ApiKeyAuth: []+ summary: Store phone API key+ tags:+ - PhoneAPIKeys+ /api-keys/{phoneAPIKeyID}:+ delete:+ consumes:+ - application/json+ description:+ Delete a phone API Key from the database and cannot be used for+ authentication anymore.+ parameters:+ - default: 32343a19-da5e-4b1b-a767-3298a73703ca+ description: ID of the phone API key+ in: path+ name: phoneAPIKeyID+ required: true+ type: string+ produces:+ - application/json+ responses:+ "204":+ description: No Content+ schema:+ $ref: "#/definitions/responses.NoContent"+ "400":+ description: Bad Request+ schema:+ $ref: "#/definitions/responses.BadRequest"+ "401":+ description: Unauthorized+ schema:+ $ref: "#/definitions/responses.Unauthorized"+ "404":+ description: Not Found+ schema:+ $ref: "#/definitions/responses.NotFound"+ "422":+ description: Unprocessable Entity+ schema:+ $ref: "#/definitions/responses.UnprocessableEntity"+ "500":+ description: Internal Server Error+ schema:+ $ref: "#/definitions/responses.InternalServerError"+ security:+ - ApiKeyAuth: []+ summary: Delete a phone API key from the database.+ tags:+ - PhoneAPIKeys+ /api-keys/{phoneAPIKeyID}/phones/{phoneID}:+ delete:+ consumes:+ - application/json+ description:+ You will need to login again to the httpSMS app on your Android+ phone with a new phone API key.+ parameters:+ - default: 32343a19-da5e-4b1b-a767-3298a73703ca+ description: ID of the phone API key+ in: path+ name: phoneAPIKeyID+ required: true+ type: string+ - default: 32343a19-da5e-4b1b-a767-3298a73703ca+ description: ID of the phone+ in: path+ name: phoneID+ required: true+ type: string+ produces:+ - application/json+ responses:+ "204":+ description: No Content+ schema:+ $ref: "#/definitions/responses.NoContent"+ "400":+ description: Bad Request+ schema:+ $ref: "#/definitions/responses.BadRequest"+ "401":+ description: Unauthorized+ schema:+ $ref: "#/definitions/responses.Unauthorized"+ "404":+ description: Not Found+ schema:+ $ref: "#/definitions/responses.NotFound"+ "422":+ description: Unprocessable Entity+ schema:+ $ref: "#/definitions/responses.UnprocessableEntity"+ "500":+ description: Internal Server Error+ schema:+ $ref: "#/definitions/responses.InternalServerError"+ security:+ - ApiKeyAuth: []+ summary: Remove the association of a phone from the phone API key.+ tags:+ - PhoneAPIKeys/billing/usage:get:consumes:@@ -2040,6 +2345,11 @@ paths:This returns the list of all messages based on the filter criteriaincluding missed callsparameters:+ - description: Cloudflare turnstile token https://www.cloudflare.com/en-gb/application-services/products/turnstile/+ in: header+ name: token+ required: true+ type: string- default: +18005550199,+18005550100description: the owner's phone numbersin: query@@ -2261,6 +2571,48 @@ paths:summary: Delete Phonetags:- Phones+ /phones/fcm-token:+ put:+ consumes:+ - application/json+ description:+ Updates the FCM token of a phone. If the phone with this number+ does not exist, a new one will be created. Think of this method like an 'upsert'+ parameters:+ - description: Payload of new FCM token.+ in: body+ name: payload+ required: true+ schema:+ $ref: "#/definitions/requests.PhoneFCMToken"+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: "#/definitions/responses.PhoneResponse"+ "400":+ description: Bad Request+ schema:+ $ref: "#/definitions/responses.BadRequest"+ "401":+ description: Unauthorized+ schema:+ $ref: "#/definitions/responses.Unauthorized"+ "422":+ description: Unprocessable Entity+ schema:+ $ref: "#/definitions/responses.UnprocessableEntity"+ "500":+ description: Internal Server Error+ schema:+ $ref: "#/definitions/responses.InternalServerError"+ security:+ - ApiKeyAuth: []+ summary: Upserts the FCM token of a phone+ tags:+ - Phones/users/{userID}/api-keys:delete:consumes:diff --git a/api/pkg/handlers/phone_api_key_handler.go b/api/pkg/handlers/phone_api_key_handler.goindex c52033af..01692148 100644--- a/api/pkg/handlers/phone_api_key_handler.go+++ b/api/pkg/handlers/phone_api_key_handler.go@@ -41,11 +41,55 @@ func NewPhoneAPIKeyHandler(// RegisterRoutes registers the routes for the PhoneAPIKeyHandlerfunc (h *PhoneAPIKeyHandler) RegisterRoutes(app *fiber.App, middlewares ...fiber.Handler) {router := app.Group("/v1/api-keys/")+ router.Get("/", h.computeRoute(middlewares, h.Index)...)router.Post("/", h.computeRoute(middlewares, h.Store)...)router.Delete("/:phoneAPIKeyID", h.computeRoute(middlewares, h.Delete)...)router.Delete("/:phoneAPIKeyID/phones/:phoneID", h.computeRoute(middlewares, h.DeletePhone)...)}+// Index returns the phone API Keys of a user+// @Summary Get the phone API keys of a user+// @Description Get list phone API keys which a user has registered on the httpSMS application+// @Security ApiKeyAuth+// @Tags PhoneAPIKeys+// @Accept json+// @Produce json+// @Param skip query int false "number of heartbeats to skip" minimum(0)+// @Param query query string false "filter api keys with name containing query"+// @Param limit query int false "number of phone api keys to return" minimum(1) maximum(100)+// @Success 200 {object} responses.PhoneAPIKeysResponse+// @Failure 400 {object} responses.BadRequest+// @Failure 401 {object} responses.Unauthorized+// @Failure 422 {object} responses.UnprocessableEntity+// @Failure 500 {object} responses.InternalServerError+// @Router /api-keys [get]+func (h *PhoneAPIKeyHandler) Index(c *fiber.Ctx) error {+ ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)+ defer span.End()++ var request requests.PhoneAPIKeyIndex+ if err := c.QueryParser(&request); err != nil {+ msg := fmt.Sprintf("cannot marshall params [%s] into %T", c.OriginalURL(), request)+ ctxLogger.Warn(stacktrace.Propagate(err, msg))+ return h.responseBadRequest(c, err)+ }++ if errors := h.validator.ValidateIndex(ctx, request.Sanitize()); len(errors) != 0 {+ msg := fmt.Sprintf("validation errors [%s], while fetching phone API keys [%+#v]", spew.Sdump(errors), request)+ ctxLogger.Warn(stacktrace.NewError(msg))+ return h.responseUnprocessableEntity(c, errors, "validation errors while fetching phone API keys")+ }++ apiKeys, err := h.service.Index(ctx, h.userIDFomContext(c), request.ToIndexParams())+ if err != nil {+ msg := fmt.Sprintf("cannot index phone API keys with params [%+#v]", request)+ ctxLogger.Error(stacktrace.Propagate(err, msg))+ return h.responseInternalServerError(c)+ }++ return h.responseOK(c, fmt.Sprintf("fetched %d phone API %s", len(apiKeys), h.pluralize("key", len(apiKeys))), apiKeys)+}+// Store a new Phone API key// @Summary Store phone API key// @Description Creates a new phone API key which can be used to log in to the httpSMS app on your Android phone@@ -54,18 +98,16 @@ func (h *PhoneAPIKeyHandler) RegisterRoutes(app *fiber.App, middlewares ...fiber// @Accept json// @Produce json// @Param payload body requests.PhoneAPIKeyStoreRequest true "Payload of new phone API key."-// @Success 200 {object} responses.Ok[*entities.PhoneAPIKey]+// @Success 200 {object} responses.PhoneAPIKeyResponse// @Failure 400 {object} responses.BadRequest// @Failure 401 {object} responses.Unauthorized// @Failure 422 {object} responses.UnprocessableEntity// @Failure 500 {object} responses.InternalServerError// @Router /api-keys [post]func (h *PhoneAPIKeyHandler) Store(c *fiber.Ctx) error {- ctx, span := h.tracer.StartFromFiberCtx(c)+ ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)defer span.End()- ctxLogger := h.tracer.CtxLogger(h.logger, span)-var request requests.PhoneAPIKeyStoreRequestif err := c.BodyParser(&request); err != nil {msg := fmt.Sprintf("cannot marshall params [%s] into %T", c.OriginalURL(), request)diff --git a/api/pkg/requests/phone_api_key_index_request.go b/api/pkg/requests/phone_api_key_index_request.gonew file mode 100644index 00000000..49649f28--- /dev/null+++ b/api/pkg/requests/phone_api_key_index_request.go@@ -0,0 +1,37 @@+package requests++import (+ "strings"++ "github.com/NdoleStudio/httpsms/pkg/repositories"+)++// PhoneAPIKeyIndex is the payload for fetching entities.PhoneAPIKey of a user+type PhoneAPIKeyIndex struct {+ request+ Skip string `json:"skip" query:"skip"`+ Query string `json:"query" query:"query"`+ Limit string `json:"limit" query:"limit"`+}++// Sanitize sets defaults to MessageOutstanding+func (input *PhoneAPIKeyIndex) Sanitize() PhoneAPIKeyIndex {+ if strings.TrimSpace(input.Limit) == "" {+ input.Limit = "1"+ }+ input.Query = strings.TrimSpace(input.Query)+ input.Skip = strings.TrimSpace(input.Skip)+ if input.Skip == "" {+ input.Skip = "0"+ }+ return *input+}++// ToIndexParams converts HeartbeatIndex to repositories.IndexParams+func (input *PhoneAPIKeyIndex) ToIndexParams() repositories.IndexParams {+ return repositories.IndexParams{+ Skip: input.getInt(input.Skip),+ Query: input.Query,+ Limit: input.getInt(input.Limit),+ }+}diff --git a/api/pkg/requests/phone_index_request.go b/api/pkg/requests/phone_index_request.goindex f978bb52..210efaf4 100644--- a/api/pkg/requests/phone_index_request.go+++ b/api/pkg/requests/phone_index_request.go@@ -17,7 +17,7 @@ type PhoneIndex struct {// Sanitize sets defaults to MessageOutstandingfunc (input *PhoneIndex) Sanitize() PhoneIndex {if strings.TrimSpace(input.Limit) == "" {- input.Limit = "1"+ input.Limit = "10"}input.Query = strings.TrimSpace(input.Query)input.Skip = strings.TrimSpace(input.Skip)diff --git a/api/pkg/responses/phone_api_key_responses.go b/api/pkg/responses/phone_api_key_responses.gonew file mode 100644index 00000000..f57eeafa--- /dev/null+++ b/api/pkg/responses/phone_api_key_responses.go@@ -0,0 +1,15 @@+package responses++import "github.com/NdoleStudio/httpsms/pkg/entities"++// PhoneAPIKeyResponse is the payload containing an entities.PhoneAPIKey+type PhoneAPIKeyResponse struct {+ response+ Data entities.PhoneAPIKey `json:"data"`+}++// PhoneAPIKeysResponse is the payload containing []entities.PhoneAPIKey+type PhoneAPIKeysResponse struct {+ response+ Data []entities.PhoneAPIKey `json:"data"`+}diff --git a/api/pkg/services/phone_api_key_service.go b/api/pkg/services/phone_api_key_service.goindex b3460478..172f5476 100644--- a/api/pkg/services/phone_api_key_service.go+++ b/api/pkg/services/phone_api_key_service.go@@ -38,6 +38,21 @@ func NewPhoneAPIKeyService(}}+// Index fetches the entities.Webhook for an entities.UserID+func (service *PhoneAPIKeyService) Index(ctx context.Context, userID entities.UserID, params repositories.IndexParams) ([]*entities.PhoneAPIKey, error) {+ ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)+ defer span.End()++ phoneAPIKeys, err := service.repository.Index(ctx, userID, params)+ if err != nil {+ msg := fmt.Sprintf("could not fetch phone API Keys with params [%+#v]", params)+ return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))+ }++ ctxLogger.Info(fmt.Sprintf("fetched [%d] phone API Keys with prams [%+#v]", len(phoneAPIKeys), params))+ return phoneAPIKeys, nil+}+// Create a new entities.PhoneAPIKeyfunc (service *PhoneAPIKeyService) Create(ctx context.Context, authContext entities.AuthContext, name string) (*entities.PhoneAPIKey, error) {ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)diff --git a/api/pkg/validators/phone_api_key_handler_validator.go b/api/pkg/validators/phone_api_key_handler_validator.goindex 47fb870e..459e7b3a 100644--- a/api/pkg/validators/phone_api_key_handler_validator.go+++ b/api/pkg/validators/phone_api_key_handler_validator.go@@ -34,6 +34,7 @@ func (validator *PhoneAPIKeyHandlerValidator) ValidateStore(_ context.Context, rData: &request,Rules: govalidator.MapData{"name": []string{+ "required","min:1","max:60",},@@ -42,3 +43,27 @@ func (validator *PhoneAPIKeyHandlerValidator) ValidateStore(_ context.Context, rreturn v.ValidateStruct()}++// ValidateIndex validates the requests.HeartbeatIndex request+func (validator *PhoneAPIKeyHandlerValidator) ValidateIndex(_ context.Context, request requests.PhoneAPIKeyIndex) url.Values {+ v := govalidator.New(govalidator.Options{+ Data: &request,+ Rules: govalidator.MapData{+ "limit": []string{+ "required",+ "numeric",+ "min:1",+ "max:100",+ },+ "skip": []string{+ "required",+ "numeric",+ "min:0",+ },+ "query": []string{+ "max:100",+ },+ },+ })+ return v.ValidateStruct()+}diff --git a/web/components/MessageThreadHeader.vue b/web/components/MessageThreadHeader.vueindex f41e7509..6cbee07a 100644--- a/web/components/MessageThreadHeader.vue+++ b/web/components/MessageThreadHeader.vue@@ -163,6 +163,18 @@</v-list-item-title></v-list-item-content></v-list-item>+ <v-list-item :to="{ name: 'phone-api-keys' }" exact>+ <v-list-item-icon class="pl-2">+ <v-icon dense>{{ mdiCellphoneKey }}</v-icon>+ </v-list-item-icon>+ <v-list-item-content class="ml-n3">+ <v-list-item-title class="pr-16 py-1">+ <span :class="{ 'pr-16': $vuetify.breakpoint.mdAndUp }">+ Phone API Keys+ </span>+ </v-list-item-title>+ </v-list-item-content>+ </v-list-item><v-list-itemv-if="$store.getters.getOwner":href="$store.getters.getAppData.appDownloadUrl"@@ -221,6 +233,7 @@ import {mdiPlus,mdiAccountCog,mdiLogout,+ mdiCellphoneKey,mdiDownload,mdiFinance,mdiBatteryChargingHigh,@@ -241,6 +254,7 @@ export default class MessageThreadHeader extends Vue {mdiAccountCog = mdiAccountCogmdiLogout = mdiLogoutmdiDownload = mdiDownload+ mdiCellphoneKey = mdiCellphoneKeymdiPackageUp = mdiPackageUpmdiCommentTextMultipleOutline = mdiCommentTextMultipleOutlinemdiFinance = mdiFinancediff --git a/web/models/api.ts b/web/models/api.tsindex 6b92cc54..7b2d542f 100644--- a/web/models/api.ts+++ b/web/models/api.ts@@ -1,5 +1,6 @@/* eslint-disable *//* tslint:disable */+// @ts-nocheck/** ---------------------------------------------------------------* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##@@ -117,7 +118,7 @@ export interface EntitiesMessage {* * DEFAULT: used the default communication SIM card* @example "DEFAULT"*/- sim: EntitiesSIM+ sim: string/** @example "pending" */status: string/** @example "mobile-terminated" */@@ -175,31 +176,33 @@ export interface EntitiesPhone {missed_call_auto_reply: string/** @example "+18005550199" */phone_number: string- sim: EntitiesSIM+ /** SIM card that received the message */+ sim: string/** @example "2022-06-05T14:26:10.303278+03:00" */updated_at: string/** @example "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" */user_id: string}-export enum EntitiesSIM {- SIM1 = 'SIM1',- SIM2 = 'SIM2',-}--export enum EntitiesSubscriptionName {- SubscriptionNameFree = 'free',- SubscriptionNameProMonthly = 'pro-monthly',- SubscriptionNameProYearly = 'pro-yearly',- SubscriptionNameUltraMonthly = 'ultra-monthly',- SubscriptionNameUltraYearly = 'ultra-yearly',- SubscriptionNameProLifetime = 'pro-lifetime',- SubscriptionName20KMonthly = '20k-monthly',- SubscriptionName100KMonthly = '100k-monthly',- SubscriptionName50KMonthly = '50k-monthly',- SubscriptionName20KYearly = '20k-yearly',- SubscriptionName100KYearly = '100k-yearly',- SubscriptionName50KYearly = '50k-yearly',+export interface EntitiesPhoneAPIKey {+ /** @example "pk_DGW8NwQp7mxKaSZ72Xq9v67SLqSbWQvckzzmK8D6rvd7NywSEkdMJtuxKyEkYnCY" */+ api_key: string+ /** @example "2022-06-05T14:26:02.302718+03:00" */+ created_at: string+ /** @example "32343a19-da5e-4b1b-a767-3298a73703cb" */+ id: string+ /** @example "Business Phone Key" */+ name: string+ /** @example ["[32343a19-da5e-4b1b-a767-3298a73703cb","32343a19-da5e-4b1b-a767-3298a73703cc]"] */+ phone_ids: string[]+ /** @example ["[+18005550199","+18005550100]"] */+ phone_numbers: string[]+ /** @example "2022-06-05T14:26:02.302718+03:00" */+ updated_at: string+ /** @example "[email protected]" */+ user_email: string+ /** @example "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" */+ user_id: string}export interface EntitiesUser {@@ -218,13 +221,15 @@ export interface EntitiesUser {/** @example true */notification_message_status_enabled: boolean/** @example true */+ notification_newsletter_enabled: boolean+ /** @example true */notification_webhook_enabled: boolean/** @example "2022-06-05T14:26:02.302718+03:00" */subscription_ends_at: string/** @example "8f9c71b8-b84e-4417-8408-a62274f65a08" */subscription_id: string/** @example "free" */- subscription_name: EntitiesSubscriptionName+ subscription_name: string/** @example "2022-06-05T14:26:02.302718+03:00" */subscription_renews_at: string/** @example "on_trial" */@@ -268,7 +273,7 @@ export interface RequestsDiscordUpdate {export interface RequestsHeartbeatStore {charging: boolean- owner: string+ phone_numbers: string[]}export interface RequestsMessageBulkSend {@@ -333,7 +338,7 @@ export interface RequestsMessageReceive {* SIM card that received the message* @example "SIM1"*/- sim: EntitiesSIM+ sim: string/*** Timestamp is the time when the event was emitted, Please send the timestamp in UTC with as much precision as possible* @example "2022-06-05T14:26:09.527976+03:00"@@ -372,6 +377,23 @@ export interface RequestsMessageThreadUpdate {is_archived: boolean}+export interface RequestsPhoneAPIKeyStoreRequest {+ /** @example "My Phone API Key" */+ name: string+}++export interface RequestsPhoneFCMToken {+ /** @example "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....." */+ fcm_token: string+ /** @example "[+18005550199]" */+ phone_number: string+ /**+ * SIM is the SIM slot of the phone in case the phone has more than 1 SIM slot+ * @example "SIM1"+ */+ sim: string+}+export interface RequestsPhoneUpsert {/** @example "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....." */fcm_token: string@@ -404,6 +426,8 @@ export interface RequestsUserNotificationUpdate {/** @example true */message_status_enabled: boolean/** @example true */+ newsletter_enabled: boolean+ /** @example true */webhook_enabled: boolean}@@ -540,6 +564,22 @@ export interface ResponsesOkString {status: string}+export interface ResponsesPhoneAPIKeyResponse {+ data: EntitiesPhoneAPIKey+ /** @example "item created successfully" */+ message: string+ /** @example "success" */+ status: string+}++export interface ResponsesPhoneAPIKeysResponse {+ data: EntitiesPhoneAPIKey[]+ /** @example "item created successfully" */+ message: string+ /** @example "success" */+ status: string+}+export interface ResponsesPhoneResponse {data: EntitiesPhone/** @example "item created successfully" */diff --git a/web/package.json b/web/package.jsonindex f45a04d7..7433bdd1 100644--- a/web/package.json+++ b/web/package.json@@ -13,7 +13,7 @@"lint:prettier": "prettier --check .","lint": "yarn lint:js && yarn lint:style && yarn lint:prettier","lintfix": "prettier --write --list-different . && yarn lint:js --fix && yarn lint:style --fix",- "api:models": "npx swagger-typescript-api -p ..\\api\\docs\\swagger.json -o ./models -n api.ts --no-client",+ "api:models": "npx swagger-typescript-api generate -p ..\\api\\docs\\swagger.json -o ./models -n api.ts --no-client","test": "jest"},"lint-staged": {@@ -63,6 +63,7 @@"@nuxtjs/eslint-module": "^4.1.0","@nuxtjs/stylelint-module": "^5.2.0","@nuxtjs/vuetify": "^1.12.3",+ "@types/qrcode": "^1.5.5","@vue/test-utils": "^1.3.6","axios": "^0.30.0","babel-core": "7.0.0-bridge.0",diff --git a/web/pages/phone-api-keys/index.vue b/web/pages/phone-api-keys/index.vuenew file mode 100644index 00000000..691edc0f--- /dev/null+++ b/web/pages/phone-api-keys/index.vue@@ -0,0 +1,474 @@+<template>+ <v-container+ fluid+ class="px-0 pt-0"+ :fill-height="$vuetify.breakpoint.lgAndUp"+ >+ <div class="w-full h-full">+ <v-app-bar height="60" :dense="$vuetify.breakpoint.mdAndDown">+ <v-btn icon to="/threads">+ <v-icon>{{ mdiArrowLeft }}</v-icon>+ </v-btn>+ <v-toolbar-title>+ <div class="py-16">Phone API Keys</div>+ </v-toolbar-title>+ <v-progress-linear+ :active="loading"+ :indeterminate="loading"+ absolute+ bottom+ ></v-progress-linear>+ </v-app-bar>+ <v-container>+ <v-row>+ <v-col cols="12" md="9" offset-md="1" xl="8" offset-xl="2">+ <div class="d-flex mt-3 mb-4">+ <v-progress-circular+ :size="24"+ :width="2"+ v-if="loading"+ color="primary"+ class="mt-2 mr-2"+ indeterminate+ ></v-progress-circular>+ <h5 class="text-h4">Phone API Keys</h5>+ <v-btn+ color="primary"+ class="ml-4 mt-1"+ @click="showCreateAPIKeyDialog = true"+ >+ <v-icon left>{{ mdiPlus }}</v-icon>+ Create API Key+ </v-btn>+ <v-dialog+ v-model="showCreateAPIKeyDialog"+ overlay-opacity="0.9"+ max-width="600px"+ >+ <v-card>+ <v-card-title>Create Phone API Key</v-card-title>+ <v-card-subtitle class="mt-2"+ >After creating the API key you can use it to login to the+ httpSMS Android app on your phone</v-card-subtitle+ >+ <v-card-text>+ <v-form>+ <v-text-field+ v-model="formPhoneApiKeyName"+ label="Name"+ placeholder="Enter a name for your API key"+ name="api-key"+ outlined+ :disabled="loading"+ :error="errorMessages.has('name')"+ :error-messages="errorMessages.get('name')"+ persistent-hint+ class="mb-n2"+ ></v-text-field>+ </v-form>+ </v-card-text>+ <v-card-actions class="mt-n4">+ <v-btn+ color="primary"+ :loading="loading"+ @click="createPhoneApiKey"+ >Create Key</v-btn+ >+ <v-spacer />+ <v-btn+ color="default"+ text+ @click="showCreateAPIKeyDialog = false"+ >Close</v-btn+ >+ </v-card-actions>+ </v-card>+ </v-dialog>+ </div>+ <p class="text--secondary">+ If you have multiple phones, you can create a unique phone API+ keys for your different Android phones. These API keys can only be+ used on the specific mobile phone when it calls the httpSMS server+ for specific actions like sending heartbeats, registering received+ messages, delivery reports etc. If you want to interact with the+ full+ <a+ class="text-decoration-none"+ target="_blank"+ href="https://api.httpsms.com"+ >httpSMS API</a+ >, use the API key under your account settings page instead+ <router-link class="text-decoration-none" to="/settings"+ >https://httpsms.com/settings</router-link+ >.+ </p>+ <v-simple-table class="mb-4 api-key-table">+ <template #default>+ <thead>+ <tr class="text-uppercase subtitle-2">+ <th class="text-left">Name</th>+ <th class="text-left">Created At</th>+ <th class="text-left">Phone Numbers</th>+ <th class="text-left">Actions</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="phoneApiKey in phoneApiKeys" :key="phoneApiKey.id">+ <td class="text-left">+ {{ phoneApiKey.name }}+ </td>+ <td>{{ phoneApiKey.created_at | timestamp }}</td>+ <td>+ <ul v-if="phoneApiKey.phone_numbers" class="ml-n3">+ <li+ v-for="phoneNumber in phoneApiKey.phone_numbers"+ :key="phoneNumber"+ class="my-3"+ >+ <b>{{ phoneNumber | phoneNumber }}</b>+ <v-btn+ class="ml-2 mt-n1"+ small+ color="error"+ @click="+ showRemovePhoneFromApiKeyDialog(+ phoneApiKey,+ phoneNumber,+ )+ "+ >+ Remove+ </v-btn>+ </li>+ </ul>+ <span v-else>-</span>+ </td>+ <td>+ <v-btn+ small+ color="primary"+ :disabled="loading"+ :loading="loading"+ @click="showPhoneApiKey(phoneApiKey)"+ >+ <v-icon left>{{ mdiEye }}</v-icon> View+ </v-btn>+ <v-btn+ class="ml-2"+ small+ :disabled="loading"+ color="error"+ @click="showDeletePhoneApiKeyDialog(phoneApiKey)"+ >+ <v-icon left>{{ mdiDelete }}</v-icon> Delete+ </v-btn>+ </td>+ </tr>+ </tbody>+ </template>+ </v-simple-table>+ </v-col>+ </v-row>+ </v-container>+ </div>+ <v-dialog+ v-model="showPhoneApiKeyQrCode"+ overlay-opacity="0.9"+ max-width="600"+ >+ <v-card>+ <v-card-title>Phone API Key QR Code</v-card-title>+ <v-card-subtitle class="mt-2"+ >Scan this QR code with the+ <a+ class="text-decoration-none"+ :href="$store.getters.getAppData.appDownloadUrl"+ >httpSMS app</a+ >+ on your Android phone to login.</v-card-subtitle+ >+ <v-card-text class="text-center">+ <v-text-field+ :value="activePhoneApiKey?.api_key"+ readonly+ name="api-key"+ outlined+ class="mb-n2"+ ></v-text-field>+ <canvas ref="qrCodeCanvas"></canvas>+ </v-card-text>+ <v-card-actions>+ <copy-button+ :value="activePhoneApiKey?.api_key"+ color="primary"+ copy-text="Copy API key"+ notification-text="Phone API Key copied successfully"+ />+ <v-spacer></v-spacer>+ <v-btn text class="mb-4" @click="showPhoneApiKeyQrCode = false"+ >Close</v-btn+ >+ </v-card-actions>+ </v-card>+ </v-dialog>+ <v-dialog+ v-model="deleteApiKeyDialog"+ overlay-opacity="0.9"+ max-width="600"+ >+ <v-card>+ <v-card-title class="text-h5 text-break">+ Are you sure you want to delete the+ <code>{{ activePhoneApiKey?.name }}</code> API Key?+ </v-card-title>+ <v-card-text>+ You will have to logout and login again on the <b>httpSMS</b> Android+ app on all of the phones which are currently using this API key.+ </v-card-text>+ <v-card-actions class="pb-4">+ <v-btn color="error" :loading="loading" @click="deleteApiKey">+ <v-icon left>{{ mdiDelete }}</v-icon>+ Delete API Key+ </v-btn>+ <v-spacer></v-spacer>+ <v-btn text @click="deleteApiKeyDialog = false"> Close </v-btn>+ </v-card-actions>+ </v-card>+ </v-dialog>+ <v-dialog+ v-model="removePhoneFromApiKeyDialog"+ overlay-opacity="0.9"+ max-width="600"+ >+ <v-card>+ <v-card-title class="text-h5 text-break">+ Are you sure you want to remove this phone number from the Phone API+ Key?+ </v-card-title>+ <v-card-text>+ This will remove the+ <code>{{ activePhoneNumber | phoneNumber }}</code> from your phone API+ key. You will have to logout and login again on the+ <b>httpSMS</b> Android app on the phone which is currently using this+ API key.+ </v-card-text>+ <v-card-actions class="pb-4">+ <v-btn+ color="error"+ :loading="loading"+ @click="removePhoneFromPhoneKey"+ >+ <v-icon left>{{ mdiDelete }}</v-icon>+ Remove Phone from key+ </v-btn>+ <v-spacer></v-spacer>+ <v-btn text @click="removePhoneFromApiKeyDialog = false">+ Close+ </v-btn>+ </v-card-actions>+ </v-card>+ </v-dialog>+ </v-container>+</template>++<script lang="ts">+import Vue from 'vue'+import * as QRCode from 'qrcode'+import {+ mdiArrowLeft,+ mdiAccountCircle,+ mdiShieldCheck,+ mdiDelete,+ mdiInformation,+ mdiPlus,+ mdiContentSave,+ mdiMicrosoftExcel,+ mdiEye,+ mdiEyeOff,+ mdiSendCheck,+ mdiCallReceived,+ mdiCallMade,+ mdiDotsVertical,+ mdiCreditCard,+ mdiSquareEditOutline,+} from '@mdi/js'+import Pusher, { Channel } from 'pusher-js'+import { AxiosError } from 'axios'+import { ErrorMessages, getErrorMessages } from '~/plugins/errors'+import {+ EntitiesPhone,+ EntitiesPhoneAPIKey,+ ResponsesUnprocessableEntity,+} from '~/models/api'++export default Vue.extend({+ name: 'PhoneApiKeysIndex',+ middleware: ['auth'],+ data() {+ return {+ mdiEye,+ mdiPlus,+ mdiEyeOff,+ mdiMicrosoftExcel,+ mdiArrowLeft,+ mdiAccountCircle,+ mdiShieldCheck,+ mdiDelete,+ mdiSendCheck,+ mdiContentSave,+ mdiCallReceived,+ mdiCallMade,+ mdiCreditCard,+ mdiInformation,+ mdiDotsVertical,+ mdiSquareEditOutline,+ formFile: null,+ loading: true,+ errorTitle: '',+ formPhoneApiKeyName: '',+ showPhoneApiKeyQrCode: false,+ errorMessages: new ErrorMessages(),+ phoneApiKeys: new Array<EntitiesPhoneAPIKey>(),+ activePhoneApiKey: null as EntitiesPhoneAPIKey | null,+ activePhoneNumber: '',+ showCreateAPIKeyDialog: false,+ deleteApiKeyDialog: false,+ removePhoneFromApiKeyDialog: false,+ webhookChannel: null as Channel | null,+ }+ },+ head() {+ return {+ title: 'Phone API keys - httpSMS',+ }+ },+ computed: {},+ async mounted() {+ await this.$store.dispatch('loadUser')+ await this.$store.dispatch('loadPhones')+ this.loadPhoneApiKeys()+ this.loading = false++ const pusher = new Pusher(this.$config.pusherKey, {+ cluster: this.$config.pusherCluster,+ })+ this.webhookChannel = pusher.subscribe(this.$store.getters.getAuthUser.id)+ this.webhookChannel.bind('phone.updated', () => {+ this.loadPhoneApiKeys()+ })+ },+ beforeDestroy() {+ if (this.webhookChannel) {+ this.webhookChannel.unsubscribe()+ }+ },+ methods: {+ showPhoneApiKey(apiKey: EntitiesPhoneAPIKey) {+ this.activePhoneApiKey = apiKey+ this.showPhoneApiKeyQrCode = true+ this.$nextTick(() => {+ this.generateQrCode(apiKey.api_key)+ })+ },+ showDeletePhoneApiKeyDialog(apiKey: EntitiesPhoneAPIKey) {+ this.activePhoneApiKey = apiKey+ this.deleteApiKeyDialog = true+ },+ showRemovePhoneFromApiKeyDialog(+ apiKey: EntitiesPhoneAPIKey,+ phoneNumber: string,+ ) {+ this.activePhoneNumber = phoneNumber+ this.activePhoneApiKey = apiKey+ this.removePhoneFromApiKeyDialog = true+ },+ generateQrCode(text: string) {+ const canvas = this.$refs.qrCodeCanvas+ console.log(canvas)+ if (canvas) {+ QRCode.toCanvas(+ canvas,+ text,+ { errorCorrectionLevel: 'H' },+ (err: any) => {+ if (err) {+ this.$store.dispatch('addNotification', {+ message: 'Failed to generate phone API key QR code',+ type: 'error',+ })+ }+ },+ )+ }+ },+ loadPhoneApiKeys() {+ this.loading = true+ this.$store+ .dispatch('indexPhoneApiKeys')+ .then((phoneApiKeys) => {+ this.phoneApiKeys = phoneApiKeys+ })+ .finally(() => {+ this.loading = false+ })+ },+ removePhoneFromPhoneKey() {+ this.loading = true+ this.$store+ .dispatch('deletePhoneFromPhoneApiKey', {+ phoneApiKeyId: this.activePhoneApiKey?.id,+ phoneId: this.$store.getters.getPhones.find(+ (phone: EntitiesPhone) =>+ phone.phone_number === this.activePhoneNumber,+ )?.id,+ })+ .then(() => {+ this.deleteApiKeyDialog = false+ this.loadPhoneApiKeys()+ })+ .finally(() => {+ this.loading = false+ })+ },+ deleteApiKey() {+ this.loading = true+ this.$store+ .dispatch('deletePhoneApiKey', this.activePhoneApiKey?.id)+ .then(() => {+ this.deleteApiKeyDialog = false+ this.loadPhoneApiKeys()+ })+ .finally(() => {+ this.loading = false+ })+ },+ createPhoneApiKey() {+ this.errorMessages = new ErrorMessages()+ this.loading = true+ this.$store+ .dispatch('storePhoneApiKey', this.formPhoneApiKeyName)+ .then(() => {+ this.formPhoneApiKeyName = ''+ this.showCreateAPIKeyDialog = false+ this.loadPhoneApiKeys()+ })+ .catch((error: AxiosError<ResponsesUnprocessableEntity>) => {+ this.errorMessages = getErrorMessages(error)+ this.loading = false+ })+ .finally(() => {+ this.loading = false+ })+ },+ },+})+</script>+<style scoped lang="scss">+.api-key-table {+ tbody {+ tr:hover {+ background-color: transparent !important;+ }+ }+}+</style>diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yamlindex cf079e4c..8923424b 100644--- a/web/pnpm-lock.yaml+++ b/web/pnpm-lock.yaml@@ -125,6 +125,9 @@ importers:'@nuxtjs/vuetify':specifier: ^1.12.3version: 1.12.3([email protected])([email protected])+ '@types/qrcode':+ specifier: ^1.5.5+ version: 1.5.5'@vue/test-utils':specifier: ^1.3.6version: 1.3.6([email protected])([email protected])@@ -3612,6 +3615,12 @@ packages:integrity: sha512-Sk/uYFOBAB7mb74XcpizmH0KOR2Pv3D2Hmrh1Dmy5BmK3MpdSa5kqZcg6EKBdklU0bFXX9gCfzvpnyUehrPIuA==,}+ '@types/[email protected]':+ resolution:+ {+ integrity: sha512-CdfBi/e3Qk+3Z/fXYShipBT13OJ2fDO2Q2w5CIP5anLTLIndQG9z6P1cnm+8zCWSpm5dnxMFd/uREtb0EXuQzg==,+ }+'@types/[email protected]':resolution:{@@ -18178,6 +18187,10 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ '@types/node': 20.8.0+'@types/[email protected]': {}'@types/[email protected]': {}diff --git a/web/store/index.ts b/web/store/index.tsindex 8bca542b..debe6bf4 100644--- a/web/store/index.ts+++ b/web/store/index.ts@@ -10,6 +10,7 @@ import {EntitiesDiscord,EntitiesMessage,EntitiesPhone,+ EntitiesPhoneAPIKey,EntitiesUser,EntitiesWebhook,RequestsDiscordStore,@@ -22,6 +23,8 @@ import {ResponsesMessagesResponse,ResponsesNoContent,ResponsesOkString,+ ResponsesPhoneAPIKeyResponse,+ ResponsesPhoneAPIKeysResponse,ResponsesUnprocessableEntity,ResponsesUserResponse,ResponsesWebhookResponse,@@ -432,6 +435,119 @@ export const actions = {})},+ storePhoneApiKey(context: ActionContext<State, State>, name: string) {+ return new Promise<ResponsesPhoneAPIKeyResponse>((resolve, reject) => {+ axios+ .post<ResponsesPhoneAPIKeyResponse>(`/v1/api-keys`, { name })+ .then(async (response: AxiosResponse<ResponsesPhoneAPIKeyResponse>) => {+ await context.dispatch('addNotification', {+ message:+ response.data.message ?? 'Phone API Key created successfully',+ type: 'success',+ })+ resolve(response.data)+ })+ .catch(async (error: AxiosError<ResponsesUnprocessableEntity>) => {+ await Promise.all([+ context.dispatch('addNotification', {+ message:+ error.response?.data?.message ??+ 'Errors while creating phone API key',+ type: 'error',+ }),+ ])+ reject(error)+ })+ })+ },++ indexPhoneApiKeys(context: ActionContext<State, State>) {+ return new Promise<Array<EntitiesPhoneAPIKey>>((resolve, reject) => {+ axios+ .get<ResponsesPhoneAPIKeysResponse>(`/v1/api-keys`, {+ params: {+ limit: 100,+ },+ })+ .then((response: AxiosResponse<ResponsesPhoneAPIKeysResponse>) => {+ resolve(response.data.data)+ })+ .catch(async (error: AxiosError) => {+ await Promise.all([+ context.dispatch('addNotification', {+ message:+ (error.response?.data as any)?.message ??+ 'Error while fetching phone API keys',+ type: 'error',+ }),+ ])+ reject(getErrorMessages(error))+ })+ })+ },++ deletePhoneApiKey(+ context: ActionContext<State, State>,+ phoneAPIKeyID: string,+ ) {+ return new Promise<void>((resolve, reject) => {+ axios+ .delete<ResponsesNoContent>(`/v1/api-keys/${phoneAPIKeyID}`)+ .then(async (response: AxiosResponse<ResponsesNoContent>) => {+ await context.dispatch('addNotification', {+ message:+ response.data.message ??+ 'The phone API key has been deleted successfully',+ type: 'success',+ })+ resolve()+ })+ .catch(async (error: AxiosError) => {+ await Promise.all([+ context.dispatch('addNotification', {+ message:+ (error.response?.data as any)?.message ??+ 'Error while deleting phone API key',+ type: 'error',+ }),+ ])+ reject(getErrorMessages(error))+ })+ })+ },++ deletePhoneFromPhoneApiKey(+ context: ActionContext<State, State>,+ payload: { phoneAPIKeyID: string; phoneID: string },+ ) {+ return new Promise<void>((resolve, reject) => {+ axios+ .delete<ResponsesNoContent>(+ `/v1/api-keys/${payload.phoneAPIKeyID}/phones/${payload.phoneID}`,+ )+ .then(async (response: AxiosResponse<ResponsesNoContent>) => {+ await context.dispatch('addNotification', {+ message:+ response.data.message ??+ 'The phone has been removed from the phone API key successfully',+ type: 'success',+ })+ resolve()+ })+ .catch(async (error: AxiosError) => {+ await Promise.all([+ context.dispatch('addNotification', {+ message:+ (error.response?.data as any)?.message ??+ 'Error while deleting phone API key',+ type: 'error',+ }),+ ])+ reject(getErrorMessages(error))+ })+ })+ },+async handleAxiosError(context: ActionContext<State, State>,error: AxiosError<ResponsesUnprocessableEntity>,