AWS |
AWS Japan Blog |
Oracle Exadata Database と Amazon RDS for Oracle 性能比較 |
https://aws.amazon.com/jp/blogs/news/comparing-oracle-exadata-database-performance-with-amazon-rds-for-oracle/
|
adata |
2023-06-04 00:20:31 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
Denoでプロセス置換付きでshellを実行するには |
https://qiita.com/nagauta/items/9353e875ad1802de654e
|
constahellonworldcon |
2023-06-04 09:21:47 |
Docker |
dockerタグが付けられた新着投稿 - Qiita |
SudoなしでDockerコマンドを実行する |
https://qiita.com/Daifukufuku/items/4ab9ad6fddb846ca60b2
|
createadockergroup |
2023-06-04 09:18:27 |
golang |
Goタグが付けられた新着投稿 - Qiita |
Go言語のテストコードのあれこれ |
https://qiita.com/takengineer1216/items/5da012332932be6096d7
|
testin |
2023-06-04 09:08:36 |
Git |
Gitタグが付けられた新着投稿 - Qiita |
[Git] 動作を試す 実行例50:pushで(チェックアウトせずに)リモートリポジトリにブランチを作成 |
https://qiita.com/dl_from_scratch/items/59c15b71b147f4149f47
|
記事 |
2023-06-04 09:46:12 |
Git |
Gitタグが付けられた新着投稿 - Qiita |
[Git] 動作を試す 実行例49:pushでリモートリポジトリのブランチ位置を強制的に移動 |
https://qiita.com/dl_from_scratch/items/a4fc0b27b5ef2abd3fe1
|
記事 |
2023-06-04 09:45:43 |
Git |
Gitタグが付けられた新着投稿 - Qiita |
[Git] 動作を試す 実行例48:リモートとローカルで別名のブランチを指定してfetch/push |
https://qiita.com/dl_from_scratch/items/c38411b9c597af795a7c
|
fetchpushgit |
2023-06-04 09:45:30 |
Git |
Gitタグが付けられた新着投稿 - Qiita |
[Git] 動作を試す 実行例47:チェックアウトせずにカレントブランチ以外のブランチをfetch更新・fetchマージ・push送信 |
https://qiita.com/dl_from_scratch/items/97027797cef50dbfbe5c
|
fetch |
2023-06-04 09:45:14 |
海外TECH |
DEV Community |
Authentication system using Golang and Sveltekit - User registration |
https://dev.to/sirneij/authentication-system-using-golang-and-sveltekit-user-registration-5981
|
Authentication system using Golang and Sveltekit User registration IntroductionWith the basic setup laid bare it s time to build a truly useful API service for our authentication system In this article we will delve into user registration storage in the database password hashing using argonid sending templated emails and generating truly random and secure tokens among others Let s get on Source codeThe source code for this series is hosted on GitHub via Sirneij go auth A fullstack session based authentication system using golang and sveltekit go auth View on GitHub Implementation Step Create the user s database schemaWe need a database table to store our application s users data To generate and migrate a schema we ll use golang migrate Kindly follow these instructions to install it on your Operating system To create a pair of migration files up and down for our user table issue the following command in your terminal and at the root of your project Documents Projects web go auth go auth backend migrate create seq ext sql dir migrations create users table seq instructs the CLI to use sequential numbering as against the default which is the Unix timestamp We opted to use sql file extensions for the generated files by passing ext The generated files will live in the migrations folder we created in the previous article and dir allows us to specify that Lastly we fed it with the real name of the files we want to create You should see two files in the migrations folder by name Kindly open the up and fill in the following schema migrations create users table up sql Add up migration script here User tableCREATE TABLE IF NOT EXISTS users id UUID NOT NULL PRIMARY KEY DEFAULT gen random uuid email TEXT NOT NULL UNIQUE password TEXT NOT NULL first name TEXT NOT NULL last name TEXT NOT NULL is active BOOLEAN DEFAULT FALSE is staff BOOLEAN DEFAULT FALSE is superuser BOOLEAN DEFAULT FALSE thumbnail TEXT NULL date joined TIMESTAMPTZ NOT NULL DEFAULT NOW CREATE INDEX IF NOT EXISTS users id email is active indx ON users id email is active Create a domain for phone data typeCREATE DOMAIN phone AS TEXT CHECK octet length VALUE BETWEEN AND AND VALUE d User details table One to one relationship CREATE TABLE user profile id UUID NOT NULL PRIMARY KEY DEFAULT gen random uuid user id UUID NOT NULL UNIQUE phone number phone NULL birth date DATE NULL github link TEXT NULL FOREIGN KEY user id REFERENCES users id ON DELETE CASCADE CREATE INDEX IF NOT EXISTS users detail id user id ON user profile id user id In the down file we should have migrations create users table down sql Add down migration script hereDROP TABLE IF EXISTS users DROP TABLE IF EXISTS user profile We have been using these schemas right from when we started the authentication series Next we need to execute the files so that those tables will be really created in our database migrate path migrations database lt DATABASE URL gt upEnsure you replace lt DATABASE URL gt with your real database URL If everything goes well your table should now be created in your database It should be noted that instead of manually migrating the database we could do that automatically at start up in the main function Step Setting up our user modelTo abstract away interacting with the database we will create some sort of model an equivalent of Django s model But before then let s create a type for our users in internal data user types go create the file as it doesn t exist yet internal data user types gopackage dataimport database sql errors time github com google uuid goauthbackend johnowolabiidogun dev internal types type UserProfile struct ID uuid UUID json id UserID uuid UUID json user id PhoneNumber string json phone number BirthDate types NullTime json birth date GithubLink string json github link type User struct ID uuid UUID json id Email string json email Password password json FirstName string json first name LastName string json last name IsActive bool json is active IsStaff bool json is staff IsSuperuser bool json is superuser Thumbnail string json thumbnail DateJoined time Time json date joined Profile UserProfile json profile type password struct plaintext string hash string type UserModel struct DB sql DB type UserID struct Id uuid UUID var ErrDuplicateEmail errors New duplicate email These are just the basic types we ll be working on within this system You will notice that there are three columns names of the fields field types and the renames of the fields in JSON The last column is very useful because in Go field names MUST start with capital letters for them to be accessible outside their package The same goes to type names Therefore we need a way to properly send field names to requesting users and Go helps with that using the built in encoding json package Notice also that our Password field was renamed to This omits that field entirely from the JSON responses it generates How cool is that We also defined a custom password type This makes it easier to generate the hash of our users passwords Then there is this not so familiar types NullTime in the UserProfile type It was defined in internal types time go internal types time gopackage typesimport fmt reflect strings time github com lib pq NullTime is an alias for pq NullTime data typetype NullTime pq NullTime Scan implements the Scanner interface for NullTimefunc nt NullTime Scan value interface error var t pq NullTime if err t Scan value err nil return err if nil then make Valid false if reflect TypeOf value nil nt NullTime t Time false else nt NullTime t Time true return nil MarshalJSON for NullTimefunc nt NullTime MarshalJSON byte error if nt Valid return byte null nil val fmt Sprintf s nt Time Format time RFC return byte val nil const dateFormat UnmarshalJSON for NullTimefunc nt NullTime UnmarshalJSON b byte error t err time Parse dateFormat strings Replace string b if err nil return err nt Time t nt Valid true return nil The reason for this is the difficulty encountered while working with possible null values for users birthdates This article explains it quite well and the code above was some modification of the code there It should be noted that to use UUID in Go you need an external package we used github com google uuid in our case so install it with go get github com google uuid Next is handling password hashing internal data user password gopackage dataimport log github com alexedwards argonid func p password Set plaintextPassword string error hash err argonid CreateHash plaintextPassword argonid DefaultParams if err nil return err p plaintext amp plaintextPassword p hash hash return nil func p password Matches plaintextPassword string bool error match err argonid ComparePasswordAndHash plaintextPassword p hash if err nil log Fatal err return match nil We used github com alexedwards argonid package to assist in hashing and matching our users passwords It s Go s implementation of argonid The Set method does the hashing when a user registers whereas Matches confirms it when such a user wants to log in To validate users inputs a very go thing to do we have internal data user validation gopackage dataimport goauthbackend johnowolabiidogun dev internal validator func ValidateEmail v validator Validator email string v Check email email email must be provided v Check validator Matches email validator EmailRX email email must be a valid email address func ValidatePasswordPlaintext v validator Validator password string v Check password password password must be provided v Check len password gt password password must be at least bytes long v Check len password lt password password must not be more than bytes long func ValidateUser v validator Validator user User v Check user FirstName first name first name must be provided v Check user LastName last name last name must be provided ValidateEmail v user Email If the plaintext password is not nil call the standalone ValidatePasswordPlaintext helper if user Password plaintext nil ValidatePasswordPlaintext v user Password plaintext The code uses another custom package to validate email password first name and last name ーthe data required during registration The custom package looks like this internal validator validator gopackage validatorimport regexp var EmailRX regexp MustCompile a zA Z amp a zA Z a zA Z a zA Z a zA Z a zA Z a zA Z type Validator struct Errors map string string New is a helper which creates a new Validator instance with an empty errors map func New Validator return amp Validator Errors make map string string Valid returns true if the errors map doesn t contain any entries func v Validator Valid bool return len v Errors AddError adds an error message to the map so long as no entry already exists for the given key func v Validator AddError key message string if exists v Errors key exists v Errors key message Check adds an error message to the map only if a validation check is not ok func v Validator Check ok bool key message string if ok v AddError key message In returns true if a specific value is in a list of strings func In value string list string bool for i range list if value list i return true return false Matches returns true if a string value matches a specific regexp pattern func Matches value string rx regexp Regexp bool return rx MatchString value Unique returns true if all string values in a slice are unique func Unique values string bool uniqueValues make map string bool for value range values uniqueValues value true return len values len uniqueValues Pretty easy to reason along with It s finally time to create the model internal data models gopackage dataimport database sql errors var ErrRecordNotFound errors New a user with these details was not found type Models struct Users UserModel func NewModels db sql DB Models return Models Users UserModel DB db With this if we have another model all we need to do is register it in Models and initialize it in NewModels Now we need to make this model accessible to our application To do this add models to our application type in main go and initialize it inside the main function cmd api main go import goauthbackend johnowolabiidogun dev internal data type application struct models data Models func main app amp application models data NewModels db That makes the models available to all route handlers and functions that implement the application type Step User registration route handlerLet s put housekeeping to good use Create a new file register go in cmd api and make it look like this cmd api register gopackage mainimport errors net http time goauthbackend johnowolabiidogun dev internal data goauthbackend johnowolabiidogun dev internal tokens goauthbackend johnowolabiidogun dev internal validator func app application registerUserHandler w http ResponseWriter r http Request Expected data from the user var input struct Email string json email FirstName string json first name LastName string json last name Password string json password Try reading the user input to JSON err app readJSON w r amp input if err nil app badRequestResponse w r err return user amp data User Email input Email FirstName input FirstName LastName input LastName Hash user password err user Password Set input Password if err nil app serverErrorResponse w r err return Validate the user input v validator New if data ValidateUser v user v Valid app failedValidationResponse w r v Errors return Save the user in the database userID err app models Users Insert user if err nil switch case errors Is err data ErrDuplicateEmail v AddError email A user with this email address already exists app failedValidationResponse w r v Errors default app serverErrorResponse w r err return Generate digit token otp err tokens GenerateOTP if err nil app logError r err err app storeInRedis activation otp Hash userID Id app config tokenExpiration duration if err nil app logError r err now time Now expiration now Add app config tokenExpiration duration exact expiration Format time RFC Send email to user using separate goroutine for account activation app background func data map string interface token tokens FormatOTP otp Secret userID userID Id frontendURL app config frontendURL expiration app config tokenExpiration durationString exact exact err app mailer Send user Email user welcome tmpl data if err nil app logError r err app logger PrintInfo Email successfully sent nil app config debug Respond with success app successResponse w r http StatusAccepted Your account creation was accepted successfully Check your email address and follow the instruction to activate your account Ensure you activate your account before the token expires Though a bit long reading through the lines gives you the whole idea We expect four fields from the user After converting them to proper JSON using readJSON a method created previously we initialized the User type set hash the supplied password and then validate the user supplied data If everything is good we used Insert a method on the User type that lives in internal data user queries go to save the user in the database The method is simple internal data user queries gopackage dataimport context database sql errors log time github com google uuid func um UserModel Insert user User UserID error ctx cancel context WithTimeout context Background time Second defer cancel tx err um DB BeginTx ctx nil if err nil return nil err var userID uuid UUID query user INSERT INTO users email password first name last name VALUES RETURNING id args user interface user Email user Password hash user FirstName user LastName if err tx QueryRowContext ctx query user args user Scan amp userID err nil switch case err Error pq duplicate key value violates unique constraint users email key return nil ErrDuplicateEmail default return nil err query user profile INSERT INTO user profile user id VALUES ON CONFLICT user id DO NOTHING RETURNING user id err tx ExecContext ctx query user profile userID if err nil return nil err if err tx Commit err nil return nil err id UserID Id userID return amp id nil We used Go s database transaction to execute our SQL queries We also provided seconds timeout for our database to finish up or get timed out If the insertion query is successful the user s ID is returned Next we generated a token for the new user The token is a random and cryptographically secure digit number which then gets encoded using the sha algorithm The entire logic is internal tokens utils gopackage tokensimport crypto rand crypto sha fmt math big strings goauthbackend johnowolabiidogun dev internal validator type Token struct Secret string Hash string func GenerateOTP Token error bigInt err rand Int rand Reader big NewInt if err nil return nil err sixDigitNum bigInt Int Convert the integer to a string and get the first characters sixDigitStr fmt Sprintf d sixDigitNum token Token Secret sixDigitStr hash sha Sum byte token Secret token Hash fmt Sprintf x n hash return amp token nil func FormatOTP s string string length len s half length firstHalf s half secondHalf s half words string firstHalf secondHalf return strings Join words func ValidateSecret v validator Validator secret string v Check secret token must be provided v Check len secret token must be bytes long After the token generation we temporarily store the token hash in redis using the storeInRedis method and then send an email in the background using a different goroutine to the user with instructions on how to activate their accounts The functions used are located in cmd api helpers go cmd api helpers go func app application storeInRedis prefix string hash string userID uuid UUID expiration time Duration error ctx context Background err app redisClient Set ctx fmt Sprintf s s prefix userID hash expiration Err if err nil return err return nil func app application background fn func app wg Add go func defer app wg Done Recover any panic defer func if err recover err nil app logger PrintError fmt Errorf s err nil app config debug Execute the arbitrary function that we passed as the parameter fn The tokens expire and get deleted from redis after TOKEN EXPIRATION has elapsed I think we should stop here as this article is getting pretty long In the next one we will implement missing methods configure our app for email sending and implement activating users accounts handler Enjoy OutroEnjoyed this article Consider contacting me for a job something worthwhile or buying a coffee You can also connect with follow me on LinkedIn and Twitter It isn t bad if you help share this article for wider coverage I will appreciate it |
2023-06-04 00:25:54 |
海外TECH |
DEV Community |
CSS Grid: A Comprehensive Guide to Flexible and Responsive Layouts |
https://dev.to/uzafar90/a-comprehensive-guide-to-using-css-grid-for-creating-flexible-and-responsive-layouts-m4b
|
CSS Grid A Comprehensive Guide to Flexible and Responsive LayoutsIn today s web development landscape creating flexible and responsive layouts is essential to ensure optimal user experience across various devices and screen sizes CSS Grid a powerful layout module introduced in CSS provides a comprehensive solution for building intricate grid based layouts with ease In this guide we will explore CSS Grid in depth and learn how to leverage its capabilities to create flexible and responsive designs Understanding CSS GridCSS Grid revolves around the concept of a grid container and grid items The grid container serves as the parent element that houses the grid while the grid items are the child elements within the grid Understanding grid tracks cells and areas as well as grid lines and gaps is crucial for effective grid layout creation Creating a Basic Grid LayoutTo set up a basic grid layout we begin by defining the grid container By specifying the number and size of grid columns and rows we establish the structure of the grid With grid template columns and grid template rows properties we can create equal width columns specify fixed or flexible sizes or utilize fractional units Once the grid structure is defined we can place grid items within the grid using various placement techniques Grid Layout TechniquesCSS Grid offers several techniques for creating dynamic and versatile layouts We explore methods such as creating equal width columns making layouts responsive by adapting to different screen sizes and utilizing named grid areas to simplify placement and alignment Working with Grid PropertiesIn this section we delve into essential grid properties that fine tune the appearance and behavior of grid layouts We discuss grid template columns and grid template rows which allow for explicit grid definitions Additionally we explore grid template areas a powerful property for visually organizing and arranging grid items We also cover grid gap and grid row gap which control the spacing between grid items Advanced Grid TechniquesTo further enhance our grid layouts we explore advanced techniques offered by CSS Grid We examine grid lines and grid spanning which enable us to span grid items across multiple tracks and control their placement precisely Additionally we discover auto sizing and fractional units which provide flexible options for determining column and row sizes We also explore grid auto placement which automatically positions grid items within the grid Making Grid Layouts ResponsiveResponsive web design is crucial in today s mobile first world We learn how to make our grid layouts responsive by utilizing media queries to adapt the grid structure and item placement based on different screen sizes By employing techniques such as fluid grids and grid template areas we can create layouts that seamlessly adjust to various devices Combining CSS Grid with Other Layout MethodsCSS Grid can be combined with other layout methods to achieve even more powerful and flexible designs We explore how to integrate CSS Flexbox alongside CSS Grid to leverage the strengths of both techniques Additionally we discuss creating grids within grids to create complex nested layouts Optimizing Grid PerformanceEfficient grid performance is crucial for delivering a smooth user experience We discuss techniques to optimize grid rendering and layout time including minimizing the number of grid items and using CSS Grid performance best practices By implementing these strategies we can ensure optimal performance while utilizing CSS Grid ConclusionCSS Grid empowers web developers to create sophisticated flexible and responsive layouts effortlessly In this comprehensive guide we have explored the key concepts techniques and properties of CSS Grid By experimenting practicing and leveraging the capabilities of CSS Grid you can unlock endless possibilities for creating visually stunning and adaptable web layouts Embrace CSS Grid and take your web design skills to new heights |
2023-06-04 00:11:47 |
海外TECH |
Engadget |
Scientists claim they're the first to transmit space-based solar power to Earth |
https://www.engadget.com/space-based-solar-power-first-successful-experiment-caltech-000046036.html?src=rss
|
Scientists claim they x re the first to transmit space based solar power to EarthThe idea of solar energy being transmitted from space is not a new one In a NASA engineer named Peter Glaser produced the first concept design for a solar powered satellite But only now years later does it appear scientists have actually carried out a successful experiment A team of researchers from Caltech announced on Thursday that their space borne prototype called the Space Solar Power Demonstrator SSPD had collected sunlight converted it into electricity and beamed it to microwave receivers installed on a rooftop on Caltech s Pasadena campus The experiment also proves that the setup which launched on January is capable of surviving the trip to space along with the harsh environment of space itself nbsp quot To the best of our knowledge no one has ever demonstrated wireless energy transfer in space even with expensive rigid structures We are doing it with flexible lightweight structures and with our own integrated circuits This is a first quot said Ali Hajimiri professor of electrical engineering and medical engineering and co director of Caltech s Space Solar Power Project SSPP in a press release published on Thursday nbsp The experiment ーknown in full as Microwave Array for Power transfer Low orbit Experiment or MAPLE for short ーis one of three research projects being carried out aboard the SSPD The effort involved two separate receiver arrays and lightweight microwave transmitters with custom chips according to Caltech In its press release the team added that the transmission setup was designed to minimize the amount of fuel needed to send them to space and that the design also needed to be flexible enough so that the transmitters could be folded up onto a rocket Space based solar power has long been something of a holy grail in the scientific community Although expensive in its current form the technology carries the promise of potentially unlimited renewable energy with solar panels in space able to collect sunlight regardless of the time of day The use of microwaves to transmit power would also mean that cloud cover wouldn t pose an interference as Nikkeinotes Caltech s Space Solar Power Project SSSP is hardly the only team that has been attempting to make space based solar power a reality Late last month a few days before Caltech s announcement Japan s space agency JAXA announced a public private partnership that aims to send solar power from space by The leader of that project a Kyoto University professor has been working on space based solar power since Japan also had a breakthrough of its own nearly a decade ago in when JAXA scientists transmitted kilowatts of power ーabout enough energy to power an electric kettle ーmore than meters to a wireless receiver nbsp The Space Solar Power Project was founded back in In addition to MAPLE the SSPD is being used to assess what types of cells are the most effective in surviving the conditions of space The third experiment is known as DOLCE Deployable on Orbit ultraLight Composite Experiment a structure measuring six by six feet that quot demonstrates the architecture packaging scheme and deployment mechanisms of the modular spacecraft quot according to Caltech It has not yet been deployed This article originally appeared on Engadget at |
2023-06-04 00:00:46 |
海外TECH |
CodeProject Latest Articles |
Cross Platform AES 256 GCM Encryption / Decryption |
https://www.codeproject.com/Articles/1265115/Cross-Platform-AES-256-GCM-Encryption-Decryption
|
decryption |
2023-06-04 00:21:00 |
ニュース |
BBC News - Home |
India train accident: Modi vows punishments over deadly Odisha crash |
https://www.bbc.co.uk/news/world-asia-india-65798640?at_medium=RSS&at_campaign=KARANGA
|
odisha |
2023-06-04 00:20:57 |
ニュース |
BBC News - Home |
Ukraine war: Twenty injured after Russian strike on Dnipro |
https://www.bbc.co.uk/news/world-europe-65800870?at_medium=RSS&at_campaign=KARANGA
|
ukrainian |
2023-06-04 00:43:58 |
ビジネス |
東洋経済オンライン |
婚活でもあらわ「高収入外国人と日本人男性」の差 外国人男性との結婚を選んだ彼女の言い分 | 激変!ニッポンの結婚 | 東洋経済オンライン |
https://toyokeizai.net/articles/-/676922?utm_source=rss&utm_medium=http&utm_campaign=link_back
|
日本人男性 |
2023-06-04 09:30:00 |
コメント
コメントを投稿