投稿時間:2022-10-29 20:10:49 RSSフィード2022-10-29 20:00 分まとめ(12件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
js JavaScriptタグが付けられた新着投稿 - Qiita 背景とテキストの色を切り替えたい https://qiita.com/y-knsr/items/1a1e0be9f981883ca113 script 2022-10-29 19:26:55
海外TECH MakeUseOf How to Screen Share With FaceTime on a Mac https://www.makeuseof.com/share-screen-facetime-mac/ facetime 2022-10-29 10:30:14
海外TECH DEV Community How to build a One-Time-Password(OTP) Verification API with Go and Twilio https://dev.to/hackmamba/how-to-build-a-one-time-passwordotp-verification-api-with-go-and-twilio-3363 How to build a One Time Password OTP Verification API with Go and TwilioOrganizations are always looking for innovative ways to tackle threats and vulnerabilities on their platform They are constantly investing in human resources and technologies to help build and ship secure applications Two factor authentication Authenticator app and Biometrics among others are some of the innovative methods organizations are adopting to keep their platform safe In this post we will learn how to build APIs that authenticate users with their phone numbers using Go and Twilio s Verification Service For this post we will be using Gin gonic to build our API However the same approach also applies to any Go based framework PrerequisitesTo fully grasp the concepts presented in this tutorial the following requirements apply Basic understanding of GoGo installation Version above A Twilio account signup for a trial account is completely free Getting startedTo get started we need to navigate to the desired directory and run the command below in our terminal mkdir go sms verification amp amp cd go sms verificationThis command creates a go sms verification folder and navigates into the project directory Next we need to initialize a Go module to manage project dependencies by running the command below go mod init go sms verificationThis command will create a go mod file for tracking project dependencies We proceed to install the required dependencies with go get github com gin gonic gin github com twilio twilio go github com joho godotenv github com go playground validator vgithub com gin gonic gin is a framework for building web application github com twilio twilio go is a Go package for communicating with Twilio github com joho godotenv is a library for managing environment variable github com go playground validator v is a library for validating structs and fields Structuring our applicationIt is essential to have a good project structure as it makes the project maintainable and makes it easier for us and others to read our codebase To do this we need to create an api cmd and data folder in our project directory api is for structuring our API related filescmd is for structuring our application entry pointdata is for structuring our application data Setting up TwilioTo enable OTP verification in our API we need to sign into our Twilio Console to get our Account SID and an Auth Token We need to keep these parameters handy as we need them to configure and build our APIs Create a Verification ServiceTwilio ships with secure and robust services for seamlessly validating users with SMS Voice and Email In our case we will use the SMS option to verify users through phone numbers To do this navigate to the Explore Products tab scroll to the Account security section and click on the Verify button Navigate to the Services tab click on the Create new button input sms service as the friendly name toggle on the SMS option and Create Upon creation we need to copy the Service SID It will also come in handy when building our API Enable geographical permissionGeographical Permissions are mechanisms put in place by Twilio to control the use of their services It provides a tool for enabling and disabling countries receiving voice calls and SMS messages from a Twilio account To enable SMS we need to search for SMS Geographic Permissions in the search bar click on the SMS Geographic Permissions result and then check the country where the SMS provider operates Creating OTP Verification APIs in GoWith the configuration done we can start building our APIs by following the steps Add environment variablesNext we need to create a env file in the root directory and add the snippet below TWILIO ACCOUNT SID lt ACCOUNT SID gt TWILIO AUTHTOKEN lt AUTH TOKEN gt TWILIO SERVICES ID lt SERVICE ID gt As mentioned earlier we can get the required credentials from Twilio console and Service Setting Finally we need to create helper functions for loading the environment variables into our application To do this we need to create a config go file inside the api folder and add the snippet below package apiimport log os github com joho godotenv func envACCOUNTSID string println godotenv Unmarshal env err godotenv Load env if err nil log Fatalln err log Fatal Error loading env file return os Getenv TWILIO ACCOUNT SID func envAUTHTOKEN string err godotenv Load if err nil log Fatal Error loading env file return os Getenv TWILIO AUTHTOKEN func envSERVICESID string err godotenv Load if err nil log Fatal Error loading env file return os Getenv TWILIO SERVICES ID The snippet above does the following Imports the required dependenciesCreate an envACCOUNTSID envAUTHTOKEN and envSERVICESID functions that check if the environment variable is correctly loaded and returns the environment variable Create the API modelsNext we need to create models to represent our application data To do this we need to navigate to the data folder and in this folder create a model go file and add the snippet below package datatype OTPData struct PhoneNumber string json phoneNumber omitempty validate required type VerifyData struct User OTPData json user omitempty validate required Code string json code omitempty validate required Create the API routes helpers service and handlersWith the models to send and verify OTP fully set up we need to navigate to the api folder and do the following First we need to create a route go file for configuring the API routes and add the snippet below package apiimport github com gin gonic gin type Config struct Router gin Engine func app Config Routes routes will come here The snippet above does the following Imports the required dependencyCreates a Config struct with a Router property to configure the application methodsCreates a Routes function that takes in the Config struct as a pointerSecondly we need to create a helper go file and add the snippet below package apiimport net http github com gin gonic gin github com go playground validator v type jsonResponse struct Status int json status Message string json message Data any json data var validate validator New func app Config validateBody c gin Context data any error validate the request body if err c BindJSON amp data err nil return err use the validator library to validate required fields if err validate Struct amp data err nil return err return nil func app Config writeJSON c gin Context status int data any c JSON status jsonResponse Status status Message success Data data func app Config errorJSON c gin Context err error status int statusCode http StatusBadRequest if len status gt statusCode status c JSON statusCode jsonResponse Status statusCode Message err Error The snippet above does the following Imports the required dependenciesCreates a jsonResponse struct and validate variable to describe the API response and to validate the API fieldsCreates a validateBody function that takes in the Config struct as a pointer and returns an error Inside the function we validate that request data in the correct format and also use the validator library to also validate and check for the required fieldsCreates a writeJSON function that takes in the Config struct as a pointer and uses the jsonResponse struct to construct API response when there s no errorCreates a errorJSON function that takes in the Config struct as a pointer and uses the jsonResponse struct to construct API response when there s an errorThirdly we need to create a service go file for abstracting the application logic and add the snippet below package apiimport github com twilio twilio go twilioApi github com twilio twilio go rest verify v var client twilio RestClient twilio NewRestClientWithParams twilio ClientParams Username envACCOUNTSID Password envAUTHTOKEN func app Config twilioSendOTP phoneNumber string string error params amp twilioApi CreateVerificationParams params SetTo phoneNumber params SetChannel sms resp err client VerifyV CreateVerification envSERVICESID params if err nil return err return resp Sid nil func app Config twilioVerifyOTP phoneNumber string code string error params amp twilioApi CreateVerificationCheckParams params SetTo phoneNumber params SetCode code resp err client VerifyV CreateVerificationCheck envSERVICESID params if err nil return err else if resp Status approved return nil return nil The snippet above does the following Imports the required dependenciesCreates a client variable to configure Twilio client using the Account SID and Auth TokenCreates a twilioSendOTP function that accepts a phoneNumber takes in the Config struct as a pointer and returns either a string or an error Inside the function we created a params variable by adding the phoneNumber and setting the channel for sending the OTP as sms Finally we use the client variable to create verification by using the Service SID and params and then return the appropriate responseCreates a twilioVerifyOTP function that accepts a phoneNumber and code takes in the Config struct as a pointer and returns an error Inside the function we created a params variable by adding the phoneNumber and code Finally we use the client variable to check authenticity of the OTP by using the Service SID and params and then return the appropriate responseFourthly we need to create a handler go file for modifying the incoming request and add the snippet below package apiimport context go sms verification data net http time github com gin gonic gin const appTimeout time Second func app Config sendSMS gin HandlerFunc return func c gin Context cancel context WithTimeout context Background appTimeout var payload data OTPData defer cancel app validateBody c amp payload newData data OTPData PhoneNumber payload PhoneNumber err app twilioSendOTP newData PhoneNumber if err nil app errorJSON c err return app writeJSON c http StatusAccepted OTP sent successfully func app Config verifySMS gin HandlerFunc return func c gin Context cancel context WithTimeout context Background appTimeout var payload data VerifyData defer cancel app validateBody c amp payload newData data VerifyData User payload User Code payload Code err app twilioVerifyOTP newData User PhoneNumber newData Code if err nil app errorJSON c err return app writeJSON c http StatusAccepted OTP verified successfully The snippet above does the following Imports the required dependenciesCreates an appTimeout variable to set request timeoutCreates a sendSMS function that returns a Gin gonic handler and takes in the Config struct as a pointer Inside the returned handler we defined the API timeout used the helper functions and the service created earlier to verify the request body and send the OTPCreates a verifySMS function that returns a Gin gonic handler and takes in the Config struct as a pointer Inside the returned handler we defined the API timeout used the helper functions and the service created earlier to verify the request body and the OTPFinally we need to update the routes go files the API route and corresponding handlerpackage apiimport github com gin gonic gin type Config struct Router gin Engine modify belowfunc app Config Routes app Router POST otp app sendSMS app Router POST verifyOTP app verifySMS Putting it all togetherWith our API fully set up we need to create the application entry point To do this we need to navigate to the cmd folder and in this folder create a main go file and add the snippet below package mainimport go sms verification api github com gin gonic gin func main router gin Default initialize config app api Config Router router routes app Routes router Run The snippet above does the following Imports the required dependenciesCreates a Gin router using the Default configuration Initialize the Config struct by passing in the RouterAdds the route and run the application on port With that done we can start a development server using the command below go run cmd main go We can also verify the message logs by navigating to the Verify tab of the Logs on Twilio ConclusionThis post discussed how to create APIs that check and verify users with their phone numbers using Go and Twilio s Verification Service Beyond SMS based verification Twilio ships multiple services to seamlessly integrate authentication into a new or existing codebase These resources might be helpful Twilio Verification ServiceTwilio go package 2022-10-29 10:07:43
海外TECH DEV Community How to build a One-Time-Password(OTP) Verification API with Rust and Twilio https://dev.to/hackmamba/how-to-build-a-one-time-passwordotp-verification-api-with-rust-and-twilio-22il How to build a One Time Password OTP Verification API with Rust and TwilioOrganizations are always looking for innovative ways to tackle threats and vulnerabilities on their platform They are constantly investing in human resources and technologies to help build and ship secure applications Two factor authentication Authenticator app and Biometrics among others are some of the innovative methods organizations are adopting to keep their platform safe In this post we will learn how to build APIs that authenticate users with their phone numbers using Rust and Twilio s Verification Service For this post we will be using Actix Web to build our API However the same approach also applies to any Rust based framework PrerequisitesTo fully grasp the concepts presented in this tutorial the following requirements apply Basic understanding of RustA Twilio account signup for a trial account is completely free Getting startedTo get started we need to navigate to the desired directory and run the command below in our terminal cargo new rust sms verification amp amp cd rust sms verificationThis command creates a Rust project called rust sms verification and navigates into the project directory Next we proceed to install the required dependencies by modifying the dependencies section of the Cargo toml file as shown below other code section goes here dependencies actix web serde version features derive dotenv reqwest version features json actix web is a Rust based framework for building web applications serde version features derive is a framework for serializing and deserializing Rust data structures E g convert Rust structs to JSON and vice versa dotenv is a crate for managing environment variables reqwest version features json is a HTTP request crate PS The feature flags used in the crates above enable a specific feature of the crate We need to run the command below to install the dependencies cargo build Structuring our applicationIt is essential to have a good project structure as it makes the project maintainable and makes it easier for us and others to read our codebase To do this we need to navigate to the src directory and in this folder create a models rs services rs and handlers rs files models rs is for structuring our application dataservices rs is for abstracting our application logichandlers rs is for structuring our APIsFinally we need to declare these files as a module and import them into the main rs file as shown below mod handlers mod models mod services fn main println Hello world Setting up TwilioTo enable OTP verification in our API we need to sign into our Twilio Console to get our Account SID and an Auth Token We need to keep these parameters handy as we need them to configure and build our APIs Create a Verification ServiceTwilio ships with secure and robust services for seamlessly validating users with SMS Voice and Email In our case we will use the SMS option to verify users through phone numbers To do this navigate to the Explore Products tab scroll to the Account security section and click on the Verify button Navigate to the Services tab click on the Create new button input sms service as the friendly name toggle on the SMS option and Create Upon creation we need to copy the Service SID It will also come in handy when building our API Enable geographical permissionGeographical Permissions are mechanisms put in place by Twilio to control the use of their services It provides a tool for enabling and disabling countries receiving voice calls and SMS messages from a Twilio account To enable SMS we need to search for SMS Geographic Permissions in the search bar click on the SMS Geographic Permissions result and then check the country where the SMS provider operates Creating OTP Verification APIs in RustWith the configuration done we can start building our APIs by following the steps Add environment variablesNext we need to create a env file in the root directory and add the snippet below TWILIO ACCOUNT SID lt ACCOUNT SID gt TWILIO AUTHTOKEN lt AUTH TOKEN gt TWILIO SERVICES ID lt SERVICE ID gt As mentioned earlier we can get the required credentials from Twilio console and Service Setting Create the API modelsNext we need to create models to represent our application data To do this we need to modify the model rs file as shown below use serde Deserialize Serialize derive Deserialize Debug Clone serde rename all camelCase pub struct OTPData pub phone number String derive Deserialize Debug Clone serde rename all camelCase pub struct VerifyOTPData pub user OTPData pub code String derive Deserialize Debug Clone pub struct OTPResponse pub sid String derive Deserialize Debug Clone pub struct OTPVerifyResponse pub status String derive Serialize Debug Clone pub struct APIResponse pub status u pub message String pub data String The snippet above does the following Imports the required dependencyCreates OTPData and VerifyOTPData structs with required properties needed for the API request body Creates OTPResponse OTPVerifyResponse and APIResponse structs with required properties needed for the API responsePS The serde rename all camelCase macro converts snake case properties to camel case and the derive macro adds implementation support for serialization deserializations and cloning Create the API serviceTwilio ships with an open API specification for accessing their services In this section we will use the Verification Service to send and verify OTP To do this first we need to update the services rs file as shown below use std collections HashMap env use dotenv dotenv use reqwest header Client use crate models OTPResponse OTPVerifyResponse pub struct TwilioService impl TwilioService fn env loader key amp str gt String dotenv ok match env var key Ok v gt v to string Err gt format Error loading env variable pub async fn send otp phone number amp String gt Result lt OTPResponse amp static str gt let account sid TwilioService env loader TWILIO ACCOUNT SID let auth token TwilioService env loader TWILIO AUTHTOKEN let service id TwilioService env loader TWILIO SERVICES ID let url format serv id Verifications serv id service id let mut headers header HeaderMap new headers insert Content Type application x www form urlencoded parse unwrap let mut form body HashMap lt amp str String gt HashMap new form body insert To phone number to string form body insert Channel sms to string let client Client new let res client post url basic auth account sid Some auth token headers headers form amp form body send await match res Ok response gt let result response json lt OTPResponse gt await match result Ok data gt Ok data Err gt Err Error sending OTP Err gt Err Error sending OTP The snippet above does the following Imports the required dependenciesCreates a TwilioService structCreates an implementation block that adds methods to the TwilioService structAdds an env loader helper method to load the environment variableAdds a send otp method that takes in the phone number as a parameter and returns the OTPResponse or a string describing the error The method also does the following Line Uses the env loader helper method to create the required environment variableLine Creates the url by formatting it with the required parameterLine Creates the API request header and sets it to a form typeLine Creates a key value pair form body to set the phone number that will receive the OTP and set the channel for sending the OTP as smsLine Creates a client instance using the reqwest library to make HTTP call to Twilio API by passing in the required authentication parameters request header and the form bodyLine Returns the appropriate responseLastly we need to add a method to verify the sent OTP as shown below imports goes herepub struct TwilioService impl TwilioService fn env loader key amp str gt String code goes here pub async fn send otp phone number amp String gt Result lt OTPResponse amp static str gt code goes here add pub async fn verify otp phone number amp String code amp String gt Result lt amp static str gt let account sid TwilioService env loader TWILIO ACCOUNT SID let auth token TwilioService env loader TWILIO AUTHTOKEN let service id TwilioService env loader TWILIO SERVICES ID let url format serv id VerificationCheck serv id service id let mut headers header HeaderMap new headers insert Content Type application x www form urlencoded parse unwrap let mut form body HashMap lt amp str amp String gt HashMap new form body insert To phone number form body insert Code code let client Client new let res client post url basic auth account sid Some auth token headers headers form amp form body send await match res Ok response gt let data response json lt OTPVerifyResponse gt await match data Ok result gt if result status approved Ok else Err Error verifying OTP Err gt Err Error verifying OTP Err gt Err Error verifying OTP The snippet above works similarly to the send otp method However we changed the url to a Verification Check URL changed the Channel to Code in the form body and returned the appropriate response by checking that the response status is approved Create the API handlersWith services fully configured we can use them to create our API handler To do this we need to update the handlers rs as shown below use actix web post web Json HttpResponse use reqwest StatusCode use crate models APIResponse OTPData VerifyOTPData services TwilioService post otp pub async fn send otp new data Json lt OTPData gt gt HttpResponse let data OTPData phone number new data phone number clone let otp details TwilioService send otp amp data phone number await match otp details Ok otp gt HttpResponse Ok json APIResponse status StatusCode ACCEPTED as u message success to string data otp sid Err e gt HttpResponse InternalServerError json APIResponse status StatusCode INTERNAL SERVER ERROR as u message failure to string data e to string post verifyOTP pub async fn verify otp new data Json lt VerifyOTPData gt gt HttpResponse let data VerifyOTPData user new data user clone code new data code clone let otp details TwilioService verify otp amp data user phone number amp data code await match otp details Ok gt HttpResponse Ok json APIResponse status StatusCode ACCEPTED as u message success to string data OTP verified successfully to string Err e gt HttpResponse InternalServerError json APIResponse status StatusCode INTERNAL SERVER ERROR as u message failure to string data e to string The snippet above does the following Imports the required dependencies Creates a send otp handler with a otp API route that uses the send otp service to send OTP and returns the appropriate response using the APIResponseCreates a verify otp handler with a verifyOTP API route that uses the verify otp service to verify OTP and returns the appropriate response using the APIResponsePutting it all togetherWith the that done we need to update the main rs file to include our application entry point and use the send otp and verify otp handlers use actix web App HttpServer adduse handlers send otp verify otp addmod handlers mod models mod services add actix web main async fn main gt std io Result lt gt HttpServer new move App new service send otp service verify otp bind run await The snippet above does the following Imports the required dependenciesCreates a new server that adds the send otp and verify otp handlers and runs on localhost With that done we can start a development server using the command below cargo run main go We can also verify the message logs by navigating to the Verify tab of the Logs on Twilio ConclusionThis post discussed how to create APIs that check and verify users with their phone numbers using Rust and Twilio s Verification Service Beyond SMS based verification Twilio ships multiple services to seamlessly integrate authentication into a new or existing codebase This resources might be helpful Twilio Verification ServiceReqwest HTTP Library 2022-10-29 10:04:09
海外TECH WIRED How to Renew Your US Passport Online https://www.wired.com/story/how-to-renew-passport-online/ application 2022-10-29 11:00:00
海外TECH WIRED What the Creator of ‘Watchmen’ Gets Right About Superhero Fans https://www.wired.com/story/alan-moore-superheroes/ heroes 2022-10-29 11:00:00
海外TECH WIRED 15 Best Deals: Coffee Makers, Projectors, and Weighted Blankets https://www.wired.com/story/weekend-deals-october-29-2022/ electric 2022-10-29 11:00:00
海外TECH WIRED Could Namor’s Ankle Wings From 'Black Panther 2' Really Work? https://www.wired.com/story/could-namors-ankle-wings-from-black-panther-2-really-work/ Could Namor s Ankle Wings From x Black Panther x Really Work Other superheroes float rocket or jump their way around the Marvel Cinematic Universeーbut this new flying method needs a physics analysis 2022-10-29 11:00:00
海外ニュース Japan Times latest articles Suspect in 2013 murder of restaurant chain president refuses to speak about case https://www.japantimes.co.jp/news/2022/10/29/national/crime-legal/police-drive-mobster-kyoto-murder/ Suspect in murder of restaurant chain president refuses to speak about caseYukio Tanaka a senior member of a group affiliated with major crime syndicate Kudo kai was arrested Friday on charges including the shooting death of Takayuki 2022-10-29 19:09:49
ニュース BBC News - Home Octopus Energy to take over collapsed supplier Bulb https://www.bbc.co.uk/news/business-63437352?at_medium=RSS&at_campaign=KARANGA bulbbulb 2022-10-29 10:48:18
ニュース BBC News - Home T20 World Cup: Sri Lanka collapse to 8-4 against NZ https://www.bbc.co.uk/sport/av/cricket/63438620?at_medium=RSS&at_campaign=KARANGA sydney 2022-10-29 10:19:00
ニュース Newsweek 北欧の雪山に「5つの太陽」が出現...神秘的な現象「幻日」が撮影される https://www.newsweekjapan.jp/stories/world/2022/10/5-1567.php アリストテレスも見た「つの偽の太陽」ハロは、明るい月明かりでも発生することがある。 2022-10-29 19:38:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)